home *** CD-ROM | disk | FTP | other *** search
/ Aminet 34 / Aminet 34 (2000)(Schatztruhe)[!][Dec 1999].iso / Aminet / dev / lang / Python152_Src.lha / Python152_Source / Python / compile.c < prev    next >
Encoding:
C/C++ Source or Header  |  1999-04-25  |  74.1 KB  |  3,467 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* Compile an expression node to intermediate code */
  33.  
  34. /* XXX TO DO:
  35.    XXX add __doc__ attribute == co_doc to code object attributes?
  36.    XXX   (it's currently the first item of the co_const tuple)
  37.    XXX Generate simple jump for break/return outside 'try...finally'
  38.    XXX Allow 'continue' inside try-finally
  39.    XXX New opcode for loading the initial index for a for loop
  40.    XXX other JAR tricks?
  41. */
  42.  
  43. #ifndef NO_PRIVATE_NAME_MANGLING
  44. #define PRIVATE_NAME_MANGLING
  45. #endif
  46.  
  47. #include "Python.h"
  48.  
  49. #include "node.h"
  50. #include "token.h"
  51. #include "graminit.h"
  52. #include "compile.h"
  53. #include "opcode.h"
  54. #include "structmember.h"
  55.  
  56. #include <ctype.h>
  57.  
  58. #include "protos/compile.h"
  59.  
  60. /* Three symbols from graminit.h are also defined in Python.h, with
  61.    Py_ prefixes to their names.  Python.h can't include graminit.h
  62.    (which defines too many confusing symbols), but we can check here
  63.    that they haven't changed (which is very unlikely, but possible). */
  64. #if Py_single_input != single_input
  65.   #error "single_input has changed -- update Py_single_input in Python.h"
  66. #endif
  67. #if Py_file_input != file_input
  68.   #error "file_input has changed -- update Py_file_input in Python.h"
  69. #endif
  70. #if Py_eval_input != eval_input
  71.   #error "eval_input has changed -- update Py_eval_input in Python.h"
  72. #endif
  73.  
  74. int Py_OptimizeFlag = 0;
  75.  
  76. #define OP_DELETE 0
  77. #define OP_ASSIGN 1
  78. #define OP_APPLY 2
  79.  
  80. #define OFF(x) offsetof(PyCodeObject, x)
  81.  
  82. static struct memberlist code_memberlist[] = {
  83.     {"co_argcount",    T_INT,        OFF(co_argcount),    READONLY},
  84.     {"co_nlocals",    T_INT,        OFF(co_nlocals),    READONLY},
  85.     {"co_stacksize",T_INT,        OFF(co_stacksize),    READONLY},
  86.     {"co_flags",    T_INT,        OFF(co_flags),        READONLY},
  87.     {"co_code",    T_OBJECT,    OFF(co_code),        READONLY},
  88.     {"co_consts",    T_OBJECT,    OFF(co_consts),        READONLY},
  89.     {"co_names",    T_OBJECT,    OFF(co_names),        READONLY},
  90.     {"co_varnames",    T_OBJECT,    OFF(co_varnames),    READONLY},
  91.     {"co_filename",    T_OBJECT,    OFF(co_filename),    READONLY},
  92.     {"co_name",    T_OBJECT,    OFF(co_name),        READONLY},
  93.     {"co_firstlineno", T_INT,    OFF(co_firstlineno),    READONLY},
  94.     {"co_lnotab",    T_OBJECT,    OFF(co_lnotab),        READONLY},
  95.     {NULL}    /* Sentinel */
  96. };
  97.  
  98. static PyObject *
  99. code_getattr(co, name)
  100.     PyCodeObject *co;
  101.     char *name;
  102. {
  103.     return PyMember_Get((char *)co, code_memberlist, name);
  104. }
  105.  
  106. static void
  107. code_dealloc(co)
  108.     PyCodeObject *co;
  109. {
  110.     Py_XDECREF(co->co_code);
  111.     Py_XDECREF(co->co_consts);
  112.     Py_XDECREF(co->co_names);
  113.     Py_XDECREF(co->co_varnames);
  114.     Py_XDECREF(co->co_filename);
  115.     Py_XDECREF(co->co_name);
  116.     Py_XDECREF(co->co_lnotab);
  117.     PyMem_DEL(co);
  118. }
  119.  
  120. static PyObject *
  121. code_repr(co)
  122.     PyCodeObject *co;
  123. {
  124.     char buf[500];
  125.     int lineno = -1;
  126.     unsigned char *p;
  127.     char *filename = "???";
  128.     char *name = "???";
  129.  
  130.     _PyCode_GETCODEPTR(co, &p);
  131.     if (*p == SET_LINENO)
  132.         lineno = (p[1] & 0xff) | ((p[2] & 0xff) << 8);
  133.     if (co->co_filename && PyString_Check(co->co_filename))
  134.         filename = PyString_AsString(co->co_filename);
  135.     if (co->co_name && PyString_Check(co->co_name))
  136.         name = PyString_AsString(co->co_name);
  137.     sprintf(buf, "<code object %.100s at %lx, file \"%.300s\", line %d>",
  138.         name, (long)co, filename, lineno);
  139.     return PyString_FromString(buf);
  140. }
  141.  
  142. static int
  143. code_compare(co, cp)
  144.     PyCodeObject *co, *cp;
  145. {
  146.     int cmp;
  147.     cmp = co->co_argcount - cp->co_argcount;
  148.     if (cmp) return cmp;
  149.     cmp = co->co_nlocals - cp->co_nlocals;
  150.     if (cmp) return cmp;
  151.     cmp = co->co_flags - cp->co_flags;
  152.     if (cmp) return cmp;
  153.     cmp = PyObject_Compare(co->co_code, cp->co_code);
  154.     if (cmp) return cmp;
  155.     cmp = PyObject_Compare(co->co_consts, cp->co_consts);
  156.     if (cmp) return cmp;
  157.     cmp = PyObject_Compare(co->co_names, cp->co_names);
  158.     if (cmp) return cmp;
  159.     cmp = PyObject_Compare(co->co_varnames, cp->co_varnames);
  160.     return cmp;
  161. }
  162.  
  163. static long
  164. code_hash(co)
  165.     PyCodeObject *co;
  166. {
  167.     long h, h1, h2, h3, h4;
  168.     h1 = PyObject_Hash(co->co_code);
  169.     if (h1 == -1) return -1;
  170.     h2 = PyObject_Hash(co->co_consts);
  171.     if (h2 == -1) return -1;
  172.     h3 = PyObject_Hash(co->co_names);
  173.     if (h3 == -1) return -1;
  174.     h4 = PyObject_Hash(co->co_varnames);
  175.     if (h4 == -1) return -1;
  176.     h = h1 ^ h2 ^ h3 ^ h4 ^
  177.         co->co_argcount ^ co->co_nlocals ^ co->co_flags;
  178.     if (h == -1) h = -2;
  179.     return h;
  180. }
  181.  
  182. PyTypeObject PyCode_Type = {
  183.     PyObject_HEAD_INIT(&PyType_Type)
  184.     0,
  185.     "code",
  186.     sizeof(PyCodeObject),
  187.     0,
  188.     (destructor)code_dealloc, /*tp_dealloc*/
  189.     0,        /*tp_print*/
  190.     (getattrfunc)code_getattr, /*tp_getattr*/
  191.     0,        /*tp_setattr*/
  192.     (cmpfunc)code_compare, /*tp_compare*/
  193.     (reprfunc)code_repr, /*tp_repr*/
  194.     0,        /*tp_as_number*/
  195.     0,        /*tp_as_sequence*/
  196.     0,        /*tp_as_mapping*/
  197.     (hashfunc)code_hash, /*tp_hash*/
  198. };
  199.  
  200. #define NAME_CHARS \
  201.     "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
  202.  
  203. PyCodeObject *
  204. PyCode_New(argcount, nlocals, stacksize, flags,
  205.           code, consts, names, varnames, filename, name,
  206.           firstlineno, lnotab)
  207.     int argcount;
  208.     int nlocals;
  209.     int stacksize;
  210.     int flags;
  211.     PyObject *code;
  212.     PyObject *consts;
  213.     PyObject *names;
  214.     PyObject *varnames;
  215.     PyObject *filename;
  216.     PyObject *name;
  217.     int firstlineno;
  218.     PyObject *lnotab;
  219. {
  220.     PyCodeObject *co;
  221.     int i;
  222.     PyBufferProcs *pb;
  223.     /* Check argument types */
  224.     if (argcount < 0 || nlocals < 0 ||
  225.         code == NULL ||
  226.         consts == NULL || !PyTuple_Check(consts) ||
  227.         names == NULL || !PyTuple_Check(names) ||
  228.         varnames == NULL || !PyTuple_Check(varnames) ||
  229.         name == NULL || !PyString_Check(name) ||
  230.         filename == NULL || !PyString_Check(filename) ||
  231.         lnotab == NULL || !PyString_Check(lnotab)) {
  232.         PyErr_BadInternalCall();
  233.         return NULL;
  234.     }
  235.     pb = code->ob_type->tp_as_buffer;
  236.     if (pb == NULL ||
  237.         pb->bf_getreadbuffer == NULL ||
  238.         pb->bf_getsegcount == NULL ||
  239.         (*pb->bf_getsegcount)(code, NULL) != 1)
  240.     {
  241.         PyErr_BadInternalCall();
  242.         return NULL;
  243.     }
  244.     /* Make sure names and varnames are all strings, & intern them */
  245.     for (i = PyTuple_Size(names); --i >= 0; ) {
  246.         PyObject *v = PyTuple_GetItem(names, i);
  247.         if (v == NULL || !PyString_Check(v)) {
  248.             PyErr_BadInternalCall();
  249.             return NULL;
  250.         }
  251.         PyString_InternInPlace(&PyTuple_GET_ITEM(names, i));
  252.     }
  253.     for (i = PyTuple_Size(varnames); --i >= 0; ) {
  254.         PyObject *v = PyTuple_GetItem(varnames, i);
  255.         if (v == NULL || !PyString_Check(v)) {
  256.             PyErr_BadInternalCall();
  257.             return NULL;
  258.         }
  259.         PyString_InternInPlace(&PyTuple_GET_ITEM(varnames, i));
  260.     }
  261.     /* Intern selected string constants */
  262.     for (i = PyTuple_Size(consts); --i >= 0; ) {
  263.         PyObject *v = PyTuple_GetItem(consts, i);
  264.         char *p;
  265.         if (!PyString_Check(v))
  266.             continue;
  267.         p = PyString_AsString(v);
  268.         if ((int)strspn(p, NAME_CHARS)
  269.             != PyString_Size(v))
  270.             continue;
  271.         PyString_InternInPlace(&PyTuple_GET_ITEM(consts, i));
  272.     }
  273.     co = PyObject_NEW(PyCodeObject, &PyCode_Type);
  274.     if (co != NULL) {
  275.         co->co_argcount = argcount;
  276.         co->co_nlocals = nlocals;
  277.         co->co_stacksize = stacksize;
  278.         co->co_flags = flags;
  279.         Py_INCREF(code);
  280.         co->co_code = code;
  281.         Py_INCREF(consts);
  282.         co->co_consts = consts;
  283.         Py_INCREF(names);
  284.         co->co_names = names;
  285.         Py_INCREF(varnames);
  286.         co->co_varnames = varnames;
  287.         Py_INCREF(filename);
  288.         co->co_filename = filename;
  289.         Py_INCREF(name);
  290.         co->co_name = name;
  291.         co->co_firstlineno = firstlineno;
  292.         Py_INCREF(lnotab);
  293.         co->co_lnotab = lnotab;
  294.     }
  295.     return co;
  296. }
  297.  
  298.  
  299. /* Data structure used internally */
  300.  
  301. struct compiling {
  302.     PyObject *c_code;        /* string */
  303.     PyObject *c_consts;    /* list of objects */
  304.     PyObject *c_names;    /* list of strings (names) */
  305.     PyObject *c_globals;    /* dictionary (value=None) */
  306.     PyObject *c_locals;    /* dictionary (value=localID) */
  307.     PyObject *c_varnames;    /* list (inverse of c_locals) */
  308.     int c_nlocals;        /* index of next local */
  309.     int c_argcount;        /* number of top-level arguments */
  310.     int c_flags;        /* same as co_flags */
  311.     int c_nexti;        /* index into c_code */
  312.     int c_errors;        /* counts errors occurred */
  313.     int c_infunction;    /* set when compiling a function */
  314.     int c_interactive;    /* generating code for interactive command */
  315.     int c_loops;        /* counts nested loops */
  316.     int c_begin;        /* begin of current loop, for 'continue' */
  317.     int c_block[CO_MAXBLOCKS]; /* stack of block types */
  318.     int c_nblocks;        /* current block stack level */
  319.     char *c_filename;    /* filename of current node */
  320.     char *c_name;        /* name of object (e.g. function) */
  321.     int c_lineno;        /* Current line number */
  322.     int c_stacklevel;    /* Current stack level */
  323.     int c_maxstacklevel;    /* Maximum stack level */
  324.     int c_firstlineno;
  325.     PyObject *c_lnotab;    /* Table mapping address to line number */
  326.     int c_last_addr, c_last_line, c_lnotab_next;
  327. #ifdef PRIVATE_NAME_MANGLING
  328.     char *c_private;    /* for private name mangling */
  329. #endif
  330. };
  331.  
  332.  
  333. /* Error message including line number */
  334.  
  335. static void
  336. com_error(c, exc, msg)
  337.     struct compiling *c;
  338.     PyObject *exc;
  339.     char *msg;
  340. {
  341.     int n = strlen(msg);
  342.     PyObject *v;
  343.     char buffer[30];
  344.     char *s;
  345.     c->c_errors++;
  346.     if (c->c_lineno <= 1) {
  347.         /* Unknown line number or single interactive command */
  348.         PyErr_SetString(exc, msg);
  349.         return;
  350.     }
  351.     sprintf(buffer, " (line %d)", c->c_lineno);
  352.     v = PyString_FromStringAndSize((char *)NULL, n + strlen(buffer));
  353.     if (v == NULL)
  354.         return; /* MemoryError, too bad */
  355.     s = PyString_AS_STRING((PyStringObject *)v);
  356.     strcpy(s, msg);
  357.     strcat(s, buffer);
  358.     PyErr_SetObject(exc, v);
  359.     Py_DECREF(v);
  360. }
  361.  
  362.  
  363. /* Interface to the block stack */
  364.  
  365. static void
  366. block_push(c, type)
  367.     struct compiling *c;
  368.     int type;
  369. {
  370.     if (c->c_nblocks >= CO_MAXBLOCKS) {
  371.         com_error(c, PyExc_SystemError,
  372.               "too many statically nested blocks");
  373.     }
  374.     else {
  375.         c->c_block[c->c_nblocks++] = type;
  376.     }
  377. }
  378.  
  379. static void
  380. block_pop(c, type)
  381.     struct compiling *c;
  382.     int type;
  383. {
  384.     if (c->c_nblocks > 0)
  385.         c->c_nblocks--;
  386.     if (c->c_block[c->c_nblocks] != type && c->c_errors == 0) {
  387.         com_error(c, PyExc_SystemError, "bad block pop");
  388.     }
  389. }
  390.  
  391.  
  392. /* Prototype forward declarations */
  393.  
  394. static int com_init Py_PROTO((struct compiling *, char *));
  395. static void com_free Py_PROTO((struct compiling *));
  396. static void com_push Py_PROTO((struct compiling *, int));
  397. static void com_pop Py_PROTO((struct compiling *, int));
  398. static void com_done Py_PROTO((struct compiling *));
  399. static void com_node Py_PROTO((struct compiling *, struct _node *));
  400. static void com_factor Py_PROTO((struct compiling *, struct _node *));
  401. static void com_addbyte Py_PROTO((struct compiling *, int));
  402. static void com_addint Py_PROTO((struct compiling *, int));
  403. static void com_addoparg Py_PROTO((struct compiling *, int, int));
  404. static void com_addfwref Py_PROTO((struct compiling *, int, int *));
  405. static void com_backpatch Py_PROTO((struct compiling *, int));
  406. static int com_add Py_PROTO((struct compiling *, PyObject *, PyObject *));
  407. static int com_addconst Py_PROTO((struct compiling *, PyObject *));
  408. static int com_addname Py_PROTO((struct compiling *, PyObject *));
  409. static void com_addopname Py_PROTO((struct compiling *, int, node *));
  410. static void com_list Py_PROTO((struct compiling *, node *, int));
  411. static int com_argdefs Py_PROTO((struct compiling *, node *));
  412. static int com_newlocal Py_PROTO((struct compiling *, char *));
  413. static PyCodeObject *icompile Py_PROTO((struct _node *, struct compiling *));
  414. static PyCodeObject *jcompile Py_PROTO((struct _node *, char *,
  415.                     struct compiling *));
  416. static PyObject *parsestrplus Py_PROTO((node *));
  417. static PyObject *parsestr Py_PROTO((char *));
  418.  
  419. static int
  420. com_init(c, filename)
  421.     struct compiling *c;
  422.     char *filename;
  423. {
  424.     if ((c->c_code = PyString_FromStringAndSize((char *)NULL,
  425.                             1000)) == NULL)
  426.         goto fail_3;
  427.     if ((c->c_consts = PyList_New(0)) == NULL)
  428.         goto fail_2;
  429.     if ((c->c_names = PyList_New(0)) == NULL)
  430.         goto fail_1;
  431.     if ((c->c_globals = PyDict_New()) == NULL)
  432.         goto fail_0;
  433.     if ((c->c_locals = PyDict_New()) == NULL)
  434.         goto fail_00;
  435.     if ((c->c_varnames = PyList_New(0)) == NULL)
  436.         goto fail_000;
  437.     if ((c->c_lnotab = PyString_FromStringAndSize((char *)NULL,
  438.                               1000)) == NULL)
  439.         goto fail_0000;
  440.     c->c_nlocals = 0;
  441.     c->c_argcount = 0;
  442.     c->c_flags = 0;
  443.     c->c_nexti = 0;
  444.     c->c_errors = 0;
  445.     c->c_infunction = 0;
  446.     c->c_interactive = 0;
  447.     c->c_loops = 0;
  448.     c->c_begin = 0;
  449.     c->c_nblocks = 0;
  450.     c->c_filename = filename;
  451.     c->c_name = "?";
  452.     c->c_lineno = 0;
  453.     c->c_stacklevel = 0;
  454.     c->c_maxstacklevel = 0;
  455.     c->c_firstlineno = 0;
  456.     c->c_last_addr = 0;
  457.     c->c_last_line = 0;
  458.     c-> c_lnotab_next = 0;
  459.     return 1;
  460.     
  461.   fail_0000:
  462.       Py_DECREF(c->c_lnotab);
  463.   fail_000:
  464.       Py_DECREF(c->c_locals);
  465.   fail_00:
  466.       Py_DECREF(c->c_globals);
  467.   fail_0:
  468.       Py_DECREF(c->c_names);
  469.   fail_1:
  470.     Py_DECREF(c->c_consts);
  471.   fail_2:
  472.     Py_DECREF(c->c_code);
  473.   fail_3:
  474.      return 0;
  475. }
  476.  
  477. static void
  478. com_free(c)
  479.     struct compiling *c;
  480. {
  481.     Py_XDECREF(c->c_code);
  482.     Py_XDECREF(c->c_consts);
  483.     Py_XDECREF(c->c_names);
  484.     Py_XDECREF(c->c_globals);
  485.     Py_XDECREF(c->c_locals);
  486.     Py_XDECREF(c->c_varnames);
  487.     Py_XDECREF(c->c_lnotab);
  488. }
  489.  
  490. static void
  491. com_push(c, n)
  492.     struct compiling *c;
  493.     int n;
  494. {
  495.     c->c_stacklevel += n;
  496.     if (c->c_stacklevel > c->c_maxstacklevel)
  497.         c->c_maxstacklevel = c->c_stacklevel;
  498. }
  499.  
  500. static void
  501. com_pop(c, n)
  502.     struct compiling *c;
  503.     int n;
  504. {
  505.     if (c->c_stacklevel < n) {
  506.         /* fprintf(stderr,
  507.             "%s:%d: underflow! nexti=%d, level=%d, n=%d\n",
  508.             c->c_filename, c->c_lineno,
  509.             c->c_nexti, c->c_stacklevel, n); */
  510.         c->c_stacklevel = 0;
  511.     }
  512.     else
  513.         c->c_stacklevel -= n;
  514. }
  515.  
  516. static void
  517. com_done(c)
  518.     struct compiling *c;
  519. {
  520.     if (c->c_code != NULL)
  521.         _PyString_Resize(&c->c_code, c->c_nexti);
  522.     if (c->c_lnotab != NULL)
  523.         _PyString_Resize(&c->c_lnotab, c->c_lnotab_next);
  524. }
  525.  
  526. static void
  527. com_addbyte(c, byte)
  528.     struct compiling *c;
  529.     int byte;
  530. {
  531.     int len;
  532.     /*fprintf(stderr, "%3d: %3d\n", c->c_nexti, byte);*/
  533.     if (byte < 0 || byte > 255) {
  534.         /*
  535.         fprintf(stderr, "XXX compiling bad byte: %d\n", byte);
  536.         fatal("com_addbyte: byte out of range");
  537.         */
  538.         com_error(c, PyExc_SystemError,
  539.               "com_addbyte: byte out of range");
  540.     }
  541.     if (c->c_code == NULL)
  542.         return;
  543.     len = PyString_Size(c->c_code);
  544.     if (c->c_nexti >= len) {
  545.         if (_PyString_Resize(&c->c_code, len+1000) != 0) {
  546.             c->c_errors++;
  547.             return;
  548.         }
  549.     }
  550.     PyString_AsString(c->c_code)[c->c_nexti++] = byte;
  551. }
  552.  
  553. static void
  554. com_addint(c, x)
  555.     struct compiling *c;
  556.     int x;
  557. {
  558.     com_addbyte(c, x & 0xff);
  559.     com_addbyte(c, x >> 8); /* XXX x should be positive */
  560. }
  561.  
  562. static void
  563. com_add_lnotab(c, addr, line)
  564.     struct compiling *c;
  565.     int addr;
  566.     int line;
  567. {
  568.     int size;
  569.     char *p;
  570.     if (c->c_lnotab == NULL)
  571.         return;
  572.     size = PyString_Size(c->c_lnotab);
  573.     if (c->c_lnotab_next+2 > size) {
  574.         if (_PyString_Resize(&c->c_lnotab, size + 1000) < 0) {
  575.             c->c_errors++;
  576.             return;
  577.         }
  578.     }
  579.     p = PyString_AsString(c->c_lnotab) + c->c_lnotab_next;
  580.     *p++ = addr;
  581.     *p++ = line;
  582.     c->c_lnotab_next += 2;
  583. }
  584.  
  585. static void
  586. com_set_lineno(c, lineno)
  587.     struct compiling *c;
  588.     int lineno;
  589. {
  590.     c->c_lineno = lineno;
  591.     if (c->c_firstlineno == 0) {
  592.         c->c_firstlineno = c->c_last_line = lineno;
  593.     }
  594.     else {
  595.         int incr_addr = c->c_nexti - c->c_last_addr;
  596.         int incr_line = lineno - c->c_last_line;
  597.         while (incr_addr > 0 || incr_line > 0) {
  598.             int trunc_addr = incr_addr;
  599.             int trunc_line = incr_line;
  600.             if (trunc_addr > 255)
  601.                 trunc_addr = 255;
  602.             if (trunc_line > 255)
  603.                 trunc_line = 255;
  604.             com_add_lnotab(c, trunc_addr, trunc_line);
  605.             incr_addr -= trunc_addr;
  606.             incr_line -= trunc_line;
  607.         }
  608.         c->c_last_addr = c->c_nexti;
  609.         c->c_last_line = lineno;
  610.     }
  611. }
  612.  
  613. static void
  614. com_addoparg(c, op, arg)
  615.     struct compiling *c;
  616.     int op;
  617.     int arg;
  618. {
  619.     if (op == SET_LINENO) {
  620.         com_set_lineno(c, arg);
  621.         if (Py_OptimizeFlag)
  622.             return;
  623.     }
  624.     com_addbyte(c, op);
  625.     com_addint(c, arg);
  626. }
  627.  
  628. static void
  629. com_addfwref(c, op, p_anchor)
  630.     struct compiling *c;
  631.     int op;
  632.     int *p_anchor;
  633. {
  634.     /* Compile a forward reference for backpatching */
  635.     int here;
  636.     int anchor;
  637.     com_addbyte(c, op);
  638.     here = c->c_nexti;
  639.     anchor = *p_anchor;
  640.     *p_anchor = here;
  641.     com_addint(c, anchor == 0 ? 0 : here - anchor);
  642. }
  643.  
  644. static void
  645. com_backpatch(c, anchor)
  646.     struct compiling *c;
  647.     int anchor; /* Must be nonzero */
  648. {
  649.     unsigned char *code = (unsigned char *) PyString_AsString(c->c_code);
  650.     int target = c->c_nexti;
  651.     int dist;
  652.     int prev;
  653.     for (;;) {
  654.         /* Make the JUMP instruction at anchor point to target */
  655.         prev = code[anchor] + (code[anchor+1] << 8);
  656.         dist = target - (anchor+2);
  657.         code[anchor] = dist & 0xff;
  658.         code[anchor+1] = dist >> 8;
  659.         if (!prev)
  660.             break;
  661.         anchor -= prev;
  662.     }
  663. }
  664.  
  665. /* Handle literals and names uniformly */
  666.  
  667. static int
  668. com_add(c, list, v)
  669.     struct compiling *c;
  670.     PyObject *list;
  671.     PyObject *v;
  672. {
  673.     int n = PyList_Size(list);
  674.     int i;
  675.     /* XXX This is quadratic in the number of names per compilation unit.
  676.        XXX Should use a dictionary. */
  677.     for (i = n; --i >= 0; ) {
  678.         PyObject *w = PyList_GetItem(list, i);
  679.         if (v->ob_type == w->ob_type && PyObject_Compare(v, w) == 0)
  680.             return i;
  681.     }
  682.     /* Check for error from PyObject_Compare */
  683.     if (PyErr_Occurred() || PyList_Append(list, v) != 0)
  684.         c->c_errors++;
  685.     return n;
  686. }
  687.  
  688. static int
  689. com_addconst(c, v)
  690.     struct compiling *c;
  691.     PyObject *v;
  692. {
  693.     return com_add(c, c->c_consts, v);
  694. }
  695.  
  696. static int
  697. com_addname(c, v)
  698.     struct compiling *c;
  699.     PyObject *v;
  700. {
  701.     return com_add(c, c->c_names, v);
  702. }
  703.  
  704. #ifdef PRIVATE_NAME_MANGLING
  705. static int
  706. com_mangle(c, name, buffer, maxlen)
  707.     struct compiling *c;
  708.     char *name;
  709.     char *buffer;
  710.     int maxlen;
  711. {
  712.     /* Name mangling: __private becomes _classname__private.
  713.        This is independent from how the name is used. */
  714.     char *p;
  715.     int nlen, plen;
  716.     nlen = strlen(name);
  717.     if (nlen+2 >= maxlen)
  718.         return 0; /* Don't mangle __extremely_long_names */
  719.     if (name[nlen-1] == '_' && name[nlen-2] == '_')
  720.         return 0; /* Don't mangle __whatever__ */
  721.     p = c->c_private;
  722.     /* Strip leading underscores from class name */
  723.     while (*p == '_')
  724.         p++;
  725.     if (*p == '\0')
  726.         return 0; /* Don't mangle if class is just underscores */
  727.     plen = strlen(p);
  728.     if (plen + nlen >= maxlen)
  729.         plen = maxlen-nlen-2; /* Truncate class name if too long */
  730.     /* buffer = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
  731.     buffer[0] = '_';
  732.     strncpy(buffer+1, p, plen);
  733.     strcpy(buffer+1+plen, name);
  734.     /* fprintf(stderr, "mangle %s -> %s\n", name, buffer); */
  735.     return 1;
  736. }
  737. #endif
  738.  
  739. static void
  740. com_addopnamestr(c, op, name)
  741.     struct compiling *c;
  742.     int op;
  743.     char *name;
  744. {
  745.     PyObject *v;
  746.     int i;
  747. #ifdef PRIVATE_NAME_MANGLING
  748.     char buffer[256];
  749.     if (name != NULL && name[0] == '_' && name[1] == '_' &&
  750.         c->c_private != NULL &&
  751.         com_mangle(c, name, buffer, (int)sizeof(buffer)))
  752.         name = buffer;
  753. #endif
  754.     if (name == NULL || (v = PyString_InternFromString(name)) == NULL) {
  755.         c->c_errors++;
  756.         i = 255;
  757.     }
  758.     else {
  759.         i = com_addname(c, v);
  760.         Py_DECREF(v);
  761.     }
  762.     /* Hack to replace *_NAME opcodes by *_GLOBAL if necessary */
  763.     switch (op) {
  764.     case LOAD_NAME:
  765.     case STORE_NAME:
  766.     case DELETE_NAME:
  767.         if (PyDict_GetItemString(c->c_globals, name) != NULL) {
  768.             switch (op) {
  769.             case LOAD_NAME:   op = LOAD_GLOBAL;   break;
  770.             case STORE_NAME:  op = STORE_GLOBAL;  break;
  771.             case DELETE_NAME: op = DELETE_GLOBAL; break;
  772.             }
  773.         }
  774.     }
  775.     com_addoparg(c, op, i);
  776. }
  777.  
  778. static void
  779. com_addopname(c, op, n)
  780.     struct compiling *c;
  781.     int op;
  782.     node *n;
  783. {
  784.     char *name;
  785.     char buffer[1000];
  786.     /* XXX it is possible to write this code without the 1000
  787.        chars on the total length of dotted names, I just can't be
  788.        bothered right now */
  789.     if (TYPE(n) == STAR)
  790.         name = "*";
  791.     else if (TYPE(n) == dotted_name) {
  792.         char *p = buffer;
  793.         int i;
  794.         name = buffer;
  795.         for (i = 0; i < NCH(n); i += 2) {
  796.             char *s = STR(CHILD(n, i));
  797.             if (p + strlen(s) > buffer + (sizeof buffer) - 2) {
  798.                 com_error(c, PyExc_MemoryError,
  799.                       "dotted_name too long");
  800.                 name = NULL;
  801.                 break;
  802.             }
  803.             if (p != buffer)
  804.                 *p++ = '.';
  805.             strcpy(p, s);
  806.             p = strchr(p, '\0');
  807.         }
  808.     }
  809.     else {
  810.         REQ(n, NAME);
  811.         name = STR(n);
  812.     }
  813.     com_addopnamestr(c, op, name);
  814. }
  815.  
  816. static PyObject *
  817. parsenumber(co, s)
  818.     struct compiling *co;
  819.     char *s;
  820. {
  821.     extern double atof Py_PROTO((const char *));
  822.     char *end;
  823.     long x;
  824.     double dx;
  825. #ifndef WITHOUT_COMPLEX
  826.     Py_complex c;
  827.     int imflag;
  828. #endif
  829.  
  830.     errno = 0;
  831.     end = s + strlen(s) - 1;
  832. #ifndef WITHOUT_COMPLEX
  833.     imflag = *end == 'j' || *end == 'J';
  834. #endif
  835.     if (*end == 'l' || *end == 'L')
  836.         return PyLong_FromString(s, (char **)0, 0);
  837.     if (s[0] == '0')
  838.         x = (long) PyOS_strtoul(s, &end, 0);
  839.     else
  840.         x = PyOS_strtol(s, &end, 0);
  841.     if (*end == '\0') {
  842.         if (errno != 0) {
  843.             com_error(co, PyExc_OverflowError,
  844.                   "integer literal too large");
  845.             return NULL;
  846.         }
  847.         return PyInt_FromLong(x);
  848.     }
  849.     /* XXX Huge floats may silently fail */
  850. #ifndef WITHOUT_COMPLEX
  851.     if (imflag) {
  852.         c.real = 0.;
  853.         PyFPE_START_PROTECT("atof", return 0)
  854.         c.imag = atof(s);
  855.         PyFPE_END_PROTECT(c)
  856.         return PyComplex_FromCComplex(c);
  857.     }
  858.     else
  859. #endif
  860.     {
  861.         PyFPE_START_PROTECT("atof", return 0)
  862.         dx = atof(s);
  863.         PyFPE_END_PROTECT(dx)
  864.         return PyFloat_FromDouble(dx);
  865.     }
  866. }
  867.  
  868. static PyObject *
  869. parsestr(s)
  870.     char *s;
  871. {
  872.     PyObject *v;
  873.     int len;
  874.     char *buf;
  875.     char *p;
  876.     char *end;
  877.     int c;
  878.     int first = *s;
  879.     int quote = first;
  880.     if (isalpha(quote) || quote == '_')
  881.         quote = *++s;
  882.     if (quote != '\'' && quote != '\"') {
  883.         PyErr_BadInternalCall();
  884.         return NULL;
  885.     }
  886.     s++;
  887.     len = strlen(s);
  888.     if (s[--len] != quote) {
  889.         PyErr_BadInternalCall();
  890.         return NULL;
  891.     }
  892.     if (len >= 4 && s[0] == quote && s[1] == quote) {
  893.         s += 2;
  894.         len -= 2;
  895.         if (s[--len] != quote || s[--len] != quote) {
  896.             PyErr_BadInternalCall();
  897.             return NULL;
  898.         }
  899.     }
  900.     if (first != quote || strchr(s, '\\') == NULL)
  901.         return PyString_FromStringAndSize(s, len);
  902.     v = PyString_FromStringAndSize((char *)NULL, len);
  903.     p = buf = PyString_AsString(v);
  904.     end = s + len;
  905.     while (s < end) {
  906.         if (*s != '\\') {
  907.             *p++ = *s++;
  908.             continue;
  909.         }
  910.         s++;
  911.         switch (*s++) {
  912.         /* XXX This assumes ASCII! */
  913.         case '\n': break;
  914.         case '\\': *p++ = '\\'; break;
  915.         case '\'': *p++ = '\''; break;
  916.         case '\"': *p++ = '\"'; break;
  917.         case 'b': *p++ = '\b'; break;
  918.         case 'f': *p++ = '\014'; break; /* FF */
  919.         case 't': *p++ = '\t'; break;
  920.         case 'n': *p++ = '\n'; break;
  921.         case 'r': *p++ = '\r'; break;
  922.         case 'v': *p++ = '\013'; break; /* VT */
  923.         case 'a': *p++ = '\007'; break; /* BEL, not classic C */
  924.         case '0': case '1': case '2': case '3':
  925.         case '4': case '5': case '6': case '7':
  926.             c = s[-1] - '0';
  927.             if ('0' <= *s && *s <= '7') {
  928.                 c = (c<<3) + *s++ - '0';
  929.                 if ('0' <= *s && *s <= '7')
  930.                     c = (c<<3) + *s++ - '0';
  931.             }
  932.             *p++ = c;
  933.             break;
  934.         case 'x':
  935.             if (isxdigit(Py_CHARMASK(*s))) {
  936.                 unsigned int x = 0;
  937.                 do {
  938.                     c = Py_CHARMASK(*s);
  939.                     s++;
  940.                     x = (x<<4) & ~0xF;
  941.                     if (isdigit(c))
  942.                         x += c - '0';
  943.                     else if (islower(c))
  944.                         x += 10 + c - 'a';
  945.                     else
  946.                         x += 10 + c - 'A';
  947.                 } while (isxdigit(Py_CHARMASK(*s)));
  948.                 *p++ = x;
  949.                 break;
  950.             }
  951.         /* FALLTHROUGH */
  952.         default: *p++ = '\\'; *p++ = s[-1]; break;
  953.         }
  954.     }
  955.     _PyString_Resize(&v, (int)(p - buf));
  956.     return v;
  957. }
  958.  
  959. static PyObject *
  960. parsestrplus(n)
  961.     node *n;
  962. {
  963.     PyObject *v;
  964.     int i;
  965.     REQ(CHILD(n, 0), STRING);
  966.     if ((v = parsestr(STR(CHILD(n, 0)))) != NULL) {
  967.         /* String literal concatenation */
  968.         for (i = 1; i < NCH(n) && v != NULL; i++) {
  969.             PyString_ConcatAndDel(&v, parsestr(STR(CHILD(n, i))));
  970.         }
  971.     }
  972.     return v;
  973. }
  974.  
  975. static void
  976. com_list_constructor(c, n)
  977.     struct compiling *c;
  978.     node *n;
  979. {
  980.     int len;
  981.     int i;
  982.     if (TYPE(n) != testlist)
  983.         REQ(n, exprlist);
  984.     /* exprlist: expr (',' expr)* [',']; likewise for testlist */
  985.     len = (NCH(n) + 1) / 2;
  986.     for (i = 0; i < NCH(n); i += 2)
  987.         com_node(c, CHILD(n, i));
  988.     com_addoparg(c, BUILD_LIST, len);
  989.     com_pop(c, len-1);
  990. }
  991.  
  992. static void
  993. com_dictmaker(c, n)
  994.     struct compiling *c;
  995.     node *n;
  996. {
  997.     int i;
  998.     /* dictmaker: test ':' test (',' test ':' value)* [','] */
  999.     for (i = 0; i+2 < NCH(n); i += 4) {
  1000.         /* We must arrange things just right for STORE_SUBSCR.
  1001.            It wants the stack to look like (value) (dict) (key) */
  1002.         com_addbyte(c, DUP_TOP);
  1003.         com_push(c, 1);
  1004.         com_node(c, CHILD(n, i+2)); /* value */
  1005.         com_addbyte(c, ROT_TWO);
  1006.         com_node(c, CHILD(n, i)); /* key */
  1007.         com_addbyte(c, STORE_SUBSCR);
  1008.         com_pop(c, 3);
  1009.     }
  1010. }
  1011.  
  1012. static void
  1013. com_atom(c, n)
  1014.     struct compiling *c;
  1015.     node *n;
  1016. {
  1017.     node *ch;
  1018.     PyObject *v;
  1019.     int i;
  1020.     REQ(n, atom);
  1021.     ch = CHILD(n, 0);
  1022.     switch (TYPE(ch)) {
  1023.     case LPAR:
  1024.         if (TYPE(CHILD(n, 1)) == RPAR) {
  1025.             com_addoparg(c, BUILD_TUPLE, 0);
  1026.             com_push(c, 1);
  1027.         }
  1028.         else
  1029.             com_node(c, CHILD(n, 1));
  1030.         break;
  1031.     case LSQB:
  1032.         if (TYPE(CHILD(n, 1)) == RSQB) {
  1033.             com_addoparg(c, BUILD_LIST, 0);
  1034.             com_push(c, 1);
  1035.         }
  1036.         else
  1037.             com_list_constructor(c, CHILD(n, 1));
  1038.         break;
  1039.     case LBRACE: /* '{' [dictmaker] '}' */
  1040.         com_addoparg(c, BUILD_MAP, 0);
  1041.         com_push(c, 1);
  1042.         if (TYPE(CHILD(n, 1)) != RBRACE)
  1043.             com_dictmaker(c, CHILD(n, 1));
  1044.         break;
  1045.     case BACKQUOTE:
  1046.         com_node(c, CHILD(n, 1));
  1047.         com_addbyte(c, UNARY_CONVERT);
  1048.         break;
  1049.     case NUMBER:
  1050.         if ((v = parsenumber(c, STR(ch))) == NULL) {
  1051.             i = 255;
  1052.         }
  1053.         else {
  1054.             i = com_addconst(c, v);
  1055.             Py_DECREF(v);
  1056.         }
  1057.         com_addoparg(c, LOAD_CONST, i);
  1058.         com_push(c, 1);
  1059.         break;
  1060.     case STRING:
  1061.         v = parsestrplus(n);
  1062.         if (v == NULL) {
  1063.             c->c_errors++;
  1064.             i = 255;
  1065.         }
  1066.         else {
  1067.             i = com_addconst(c, v);
  1068.             Py_DECREF(v);
  1069.         }
  1070.         com_addoparg(c, LOAD_CONST, i);
  1071.         com_push(c, 1);
  1072.         break;
  1073.     case NAME:
  1074.         com_addopname(c, LOAD_NAME, ch);
  1075.         com_push(c, 1);
  1076.         break;
  1077.     default:
  1078.         /* XXX fprintf(stderr, "node type %d\n", TYPE(ch)); */
  1079.         com_error(c, PyExc_SystemError,
  1080.               "com_atom: unexpected node type");
  1081.     }
  1082. }
  1083.  
  1084. static void
  1085. com_slice(c, n, op)
  1086.     struct compiling *c;
  1087.     node *n;
  1088.     int op;
  1089. {
  1090.     if (NCH(n) == 1) {
  1091.         com_addbyte(c, op);
  1092.     }
  1093.     else if (NCH(n) == 2) {
  1094.         if (TYPE(CHILD(n, 0)) != COLON) {
  1095.             com_node(c, CHILD(n, 0));
  1096.             com_addbyte(c, op+1);
  1097.         }
  1098.         else {
  1099.             com_node(c, CHILD(n, 1));
  1100.             com_addbyte(c, op+2);
  1101.         }
  1102.         com_pop(c, 1);
  1103.     }
  1104.     else {
  1105.         com_node(c, CHILD(n, 0));
  1106.         com_node(c, CHILD(n, 2));
  1107.         com_addbyte(c, op+3);
  1108.         com_pop(c, 2);
  1109.     }
  1110. }
  1111.  
  1112. static void
  1113. com_argument(c, n, pkeywords)
  1114.     struct compiling *c;
  1115.     node *n; /* argument */
  1116.     PyObject **pkeywords;
  1117. {
  1118.     node *m;
  1119.     REQ(n, argument); /* [test '='] test; really [keyword '='] test */
  1120.     if (NCH(n) == 1) {
  1121.         if (*pkeywords != NULL) {
  1122.             com_error(c, PyExc_SyntaxError,
  1123.                    "non-keyword arg after keyword arg");
  1124.         }
  1125.         else {
  1126.             com_node(c, CHILD(n, 0));
  1127.         }
  1128.         return;
  1129.     }
  1130.     m = n;
  1131.     do {
  1132.         m = CHILD(m, 0);
  1133.     } while (NCH(m) == 1);
  1134.     if (TYPE(m) != NAME) {
  1135.         com_error(c, PyExc_SyntaxError,
  1136.               "keyword can't be an expression");
  1137.     }
  1138.     else {
  1139.         PyObject *v = PyString_InternFromString(STR(m));
  1140.         if (v != NULL && *pkeywords == NULL)
  1141.             *pkeywords = PyDict_New();
  1142.         if (v == NULL || *pkeywords == NULL)
  1143.             c->c_errors++;
  1144.         else {
  1145.             if (PyDict_GetItem(*pkeywords, v) != NULL)
  1146.                 com_error(c, PyExc_SyntaxError,
  1147.                       "duplicate keyword argument");
  1148.             else
  1149.                 if (PyDict_SetItem(*pkeywords, v, v) != 0)
  1150.                     c->c_errors++;
  1151.             com_addoparg(c, LOAD_CONST, com_addconst(c, v));
  1152.             com_push(c, 1);
  1153.             Py_DECREF(v);
  1154.         }
  1155.     }
  1156.     com_node(c, CHILD(n, 2));
  1157. }
  1158.  
  1159. static void
  1160. com_call_function(c, n)
  1161.     struct compiling *c;
  1162.     node *n; /* EITHER arglist OR ')' */
  1163. {
  1164.     if (TYPE(n) == RPAR) {
  1165.         com_addoparg(c, CALL_FUNCTION, 0);
  1166.     }
  1167.     else {
  1168.         PyObject *keywords = NULL;
  1169.         int i, na, nk;
  1170.         int lineno = n->n_lineno;
  1171.         REQ(n, arglist);
  1172.         na = 0;
  1173.         nk = 0;
  1174.         for (i = 0; i < NCH(n); i += 2) {
  1175.             node *ch = CHILD(n, i);
  1176.             if (ch->n_lineno != lineno) {
  1177.                 lineno = ch->n_lineno;
  1178.                 com_addoparg(c, SET_LINENO, lineno);
  1179.             }
  1180.             com_argument(c, ch, &keywords);
  1181.             if (keywords == NULL)
  1182.                 na++;
  1183.             else
  1184.                 nk++;
  1185.         }
  1186.         Py_XDECREF(keywords);
  1187.         if (na > 255 || nk > 255) {
  1188.             com_error(c, PyExc_SyntaxError,
  1189.                   "more than 255 arguments");
  1190.         }
  1191.         com_addoparg(c, CALL_FUNCTION, na | (nk << 8));
  1192.         com_pop(c, na + 2*nk);
  1193.     }
  1194. }
  1195.  
  1196. static void
  1197. com_select_member(c, n)
  1198.     struct compiling *c;
  1199.     node *n;
  1200. {
  1201.     com_addopname(c, LOAD_ATTR, n);
  1202. }
  1203.  
  1204. static void
  1205. com_sliceobj(c, n)
  1206.     struct compiling *c;
  1207.     node *n;
  1208. {
  1209.     int i=0;
  1210.     int ns=2; /* number of slice arguments */
  1211.     node *ch;
  1212.  
  1213.     /* first argument */
  1214.     if (TYPE(CHILD(n,i)) == COLON) {
  1215.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  1216.         com_push(c, 1);
  1217.         i++;
  1218.     }
  1219.     else {
  1220.         com_node(c, CHILD(n,i));
  1221.         i++;
  1222.         REQ(CHILD(n,i),COLON);
  1223.         i++;
  1224.     }
  1225.     /* second argument */
  1226.     if (i < NCH(n) && TYPE(CHILD(n,i)) == test) {
  1227.         com_node(c, CHILD(n,i));
  1228.         i++;
  1229.     }
  1230.     else {
  1231.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  1232.         com_push(c, 1);
  1233.     }
  1234.     /* remaining arguments */
  1235.     for (; i < NCH(n); i++) {
  1236.         ns++;
  1237.         ch=CHILD(n,i);
  1238.         REQ(ch, sliceop);
  1239.         if (NCH(ch) == 1) {
  1240.             /* right argument of ':' missing */
  1241.             com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  1242.             com_push(c, 1);
  1243.         }
  1244.         else
  1245.             com_node(c, CHILD(ch,1));
  1246.     }
  1247.     com_addoparg(c, BUILD_SLICE, ns);
  1248.     com_pop(c, 1 + (ns == 3));
  1249. }
  1250.  
  1251. static void
  1252. com_subscript(c, n)
  1253.     struct compiling *c;
  1254.     node *n;
  1255. {
  1256.     node *ch;
  1257.     REQ(n, subscript);
  1258.     ch = CHILD(n,0);
  1259.     /* check for rubber index */
  1260.     if (TYPE(ch) == DOT && TYPE(CHILD(n,1)) == DOT) {
  1261.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_Ellipsis));
  1262.         com_push(c, 1);
  1263.     }
  1264.     else {
  1265.         /* check for slice */
  1266.         if ((TYPE(ch) == COLON || NCH(n) > 1))
  1267.             com_sliceobj(c, n);
  1268.         else {
  1269.             REQ(ch, test);
  1270.             com_node(c, ch);
  1271.         }
  1272.     }
  1273. }
  1274.  
  1275. static void
  1276. com_subscriptlist(c, n, assigning)
  1277.     struct compiling *c;
  1278.     node *n;
  1279.     int assigning;
  1280. {
  1281.     int i, op;
  1282.     REQ(n, subscriptlist);
  1283.     /* Check to make backward compatible slice behavior for '[i:j]' */
  1284.     if (NCH(n) == 1) {
  1285.         node *sub = CHILD(n, 0); /* subscript */
  1286.         /* Make it is a simple slice.
  1287.            Should have exactly one colon. */
  1288.         if ((TYPE(CHILD(sub, 0)) == COLON
  1289.              || (NCH(sub) > 1 && TYPE(CHILD(sub, 1)) == COLON))
  1290.             && (TYPE(CHILD(sub,NCH(sub)-1)) != sliceop))
  1291.     {
  1292.             if (assigning == OP_APPLY)
  1293.                 op = SLICE;
  1294.             else
  1295.                 op = ((assigning == OP_ASSIGN) ?
  1296.                       STORE_SLICE : DELETE_SLICE);
  1297.             com_slice(c, sub, op);
  1298.             if (op == STORE_SLICE)
  1299.                 com_pop(c, 2);
  1300.             else if (op == DELETE_SLICE)
  1301.                 com_pop(c, 1);
  1302.             return;
  1303.         }
  1304.     }
  1305.     /* Else normal subscriptlist.  Compile each subscript. */
  1306.     for (i = 0; i < NCH(n); i += 2)
  1307.         com_subscript(c, CHILD(n, i));
  1308.     /* Put multiple subscripts into a tuple */
  1309.     if (NCH(n) > 1) {
  1310.         i = (NCH(n)+1) / 2;
  1311.         com_addoparg(c, BUILD_TUPLE, i);
  1312.         com_pop(c, i-1);
  1313.     }
  1314.     if (assigning == OP_APPLY) {
  1315.         op = BINARY_SUBSCR;
  1316.         i = 1;
  1317.     }
  1318.     else if (assigning == OP_ASSIGN) {
  1319.         op = STORE_SUBSCR;
  1320.         i = 3;
  1321.     }
  1322.     else {
  1323.         op = DELETE_SUBSCR;
  1324.         i = 2;
  1325.     }
  1326.     com_addbyte(c, op);
  1327.     com_pop(c, i);
  1328. }
  1329.  
  1330. static void
  1331. com_apply_trailer(c, n)
  1332.     struct compiling *c;
  1333.     node *n;
  1334. {
  1335.     REQ(n, trailer);
  1336.     switch (TYPE(CHILD(n, 0))) {
  1337.     case LPAR:
  1338.         com_call_function(c, CHILD(n, 1));
  1339.         break;
  1340.     case DOT:
  1341.         com_select_member(c, CHILD(n, 1));
  1342.         break;
  1343.     case LSQB:
  1344.         com_subscriptlist(c, CHILD(n, 1), OP_APPLY);
  1345.         break;
  1346.     default:
  1347.         com_error(c, PyExc_SystemError,
  1348.               "com_apply_trailer: unknown trailer type");
  1349.     }
  1350. }
  1351.  
  1352. static void
  1353. com_power(c, n)
  1354.     struct compiling *c;
  1355.     node *n;
  1356. {
  1357.     int i;
  1358.     REQ(n, power);
  1359.     com_atom(c, CHILD(n, 0));
  1360.     for (i = 1; i < NCH(n); i++) {
  1361.         if (TYPE(CHILD(n, i)) == DOUBLESTAR) {
  1362.             com_factor(c, CHILD(n, i+1));
  1363.             com_addbyte(c, BINARY_POWER);
  1364.             com_pop(c, 1);
  1365.             break;
  1366.         }
  1367.         else
  1368.             com_apply_trailer(c, CHILD(n, i));
  1369.     }
  1370. }
  1371.  
  1372. static void
  1373. com_factor(c, n)
  1374.     struct compiling *c;
  1375.     node *n;
  1376. {
  1377.     REQ(n, factor);
  1378.     if (TYPE(CHILD(n, 0)) == PLUS) {
  1379.         com_factor(c, CHILD(n, 1));
  1380.         com_addbyte(c, UNARY_POSITIVE);
  1381.     }
  1382.     else if (TYPE(CHILD(n, 0)) == MINUS) {
  1383.         com_factor(c, CHILD(n, 1));
  1384.         com_addbyte(c, UNARY_NEGATIVE);
  1385.     }
  1386.     else if (TYPE(CHILD(n, 0)) == TILDE) {
  1387.         com_factor(c, CHILD(n, 1));
  1388.         com_addbyte(c, UNARY_INVERT);
  1389.     }
  1390.     else {
  1391.         com_power(c, CHILD(n, 0));
  1392.     }
  1393. }
  1394.  
  1395. static void
  1396. com_term(c, n)
  1397.     struct compiling *c;
  1398.     node *n;
  1399. {
  1400.     int i;
  1401.     int op;
  1402.     REQ(n, term);
  1403.     com_factor(c, CHILD(n, 0));
  1404.     for (i = 2; i < NCH(n); i += 2) {
  1405.         com_factor(c, CHILD(n, i));
  1406.         switch (TYPE(CHILD(n, i-1))) {
  1407.         case STAR:
  1408.             op = BINARY_MULTIPLY;
  1409.             break;
  1410.         case SLASH:
  1411.             op = BINARY_DIVIDE;
  1412.             break;
  1413.         case PERCENT:
  1414.             op = BINARY_MODULO;
  1415.             break;
  1416.         default:
  1417.             com_error(c, PyExc_SystemError,
  1418.                   "com_term: operator not *, / or %");
  1419.             op = 255;
  1420.         }
  1421.         com_addbyte(c, op);
  1422.         com_pop(c, 1);
  1423.     }
  1424. }
  1425.  
  1426. static void
  1427. com_arith_expr(c, n)
  1428.     struct compiling *c;
  1429.     node *n;
  1430. {
  1431.     int i;
  1432.     int op;
  1433.     REQ(n, arith_expr);
  1434.     com_term(c, CHILD(n, 0));
  1435.     for (i = 2; i < NCH(n); i += 2) {
  1436.         com_term(c, CHILD(n, i));
  1437.         switch (TYPE(CHILD(n, i-1))) {
  1438.         case PLUS:
  1439.             op = BINARY_ADD;
  1440.             break;
  1441.         case MINUS:
  1442.             op = BINARY_SUBTRACT;
  1443.             break;
  1444.         default:
  1445.             com_error(c, PyExc_SystemError,
  1446.                   "com_arith_expr: operator not + or -");
  1447.             op = 255;
  1448.         }
  1449.         com_addbyte(c, op);
  1450.         com_pop(c, 1);
  1451.     }
  1452. }
  1453.  
  1454. static void
  1455. com_shift_expr(c, n)
  1456.     struct compiling *c;
  1457.     node *n;
  1458. {
  1459.     int i;
  1460.     int op;
  1461.     REQ(n, shift_expr);
  1462.     com_arith_expr(c, CHILD(n, 0));
  1463.     for (i = 2; i < NCH(n); i += 2) {
  1464.         com_arith_expr(c, CHILD(n, i));
  1465.         switch (TYPE(CHILD(n, i-1))) {
  1466.         case LEFTSHIFT:
  1467.             op = BINARY_LSHIFT;
  1468.             break;
  1469.         case RIGHTSHIFT:
  1470.             op = BINARY_RSHIFT;
  1471.             break;
  1472.         default:
  1473.             com_error(c, PyExc_SystemError,
  1474.                   "com_shift_expr: operator not << or >>");
  1475.             op = 255;
  1476.         }
  1477.         com_addbyte(c, op);
  1478.         com_pop(c, 1);
  1479.     }
  1480. }
  1481.  
  1482. static void
  1483. com_and_expr(c, n)
  1484.     struct compiling *c;
  1485.     node *n;
  1486. {
  1487.     int i;
  1488.     int op;
  1489.     REQ(n, and_expr);
  1490.     com_shift_expr(c, CHILD(n, 0));
  1491.     for (i = 2; i < NCH(n); i += 2) {
  1492.         com_shift_expr(c, CHILD(n, i));
  1493.         if (TYPE(CHILD(n, i-1)) == AMPER) {
  1494.             op = BINARY_AND;
  1495.         }
  1496.         else {
  1497.             com_error(c, PyExc_SystemError,
  1498.                   "com_and_expr: operator not &");
  1499.             op = 255;
  1500.         }
  1501.         com_addbyte(c, op);
  1502.         com_pop(c, 1);
  1503.     }
  1504. }
  1505.  
  1506. static void
  1507. com_xor_expr(c, n)
  1508.     struct compiling *c;
  1509.     node *n;
  1510. {
  1511.     int i;
  1512.     int op;
  1513.     REQ(n, xor_expr);
  1514.     com_and_expr(c, CHILD(n, 0));
  1515.     for (i = 2; i < NCH(n); i += 2) {
  1516.         com_and_expr(c, CHILD(n, i));
  1517.         if (TYPE(CHILD(n, i-1)) == CIRCUMFLEX) {
  1518.             op = BINARY_XOR;
  1519.         }
  1520.         else {
  1521.             com_error(c, PyExc_SystemError,
  1522.                   "com_xor_expr: operator not ^");
  1523.             op = 255;
  1524.         }
  1525.         com_addbyte(c, op);
  1526.         com_pop(c, 1);
  1527.     }
  1528. }
  1529.  
  1530. static void
  1531. com_expr(c, n)
  1532.     struct compiling *c;
  1533.     node *n;
  1534. {
  1535.     int i;
  1536.     int op;
  1537.     REQ(n, expr);
  1538.     com_xor_expr(c, CHILD(n, 0));
  1539.     for (i = 2; i < NCH(n); i += 2) {
  1540.         com_xor_expr(c, CHILD(n, i));
  1541.         if (TYPE(CHILD(n, i-1)) == VBAR) {
  1542.             op = BINARY_OR;
  1543.         }
  1544.         else {
  1545.             com_error(c, PyExc_SystemError,
  1546.                   "com_expr: expr operator not |");
  1547.             op = 255;
  1548.         }
  1549.         com_addbyte(c, op);
  1550.         com_pop(c, 1);
  1551.     }
  1552. }
  1553.  
  1554. static enum cmp_op
  1555. cmp_type(n)
  1556.     node *n;
  1557. {
  1558.     REQ(n, comp_op);
  1559.     /* comp_op: '<' | '>' | '=' | '>=' | '<=' | '<>' | '!=' | '=='
  1560.               | 'in' | 'not' 'in' | 'is' | 'is' not' */
  1561.     if (NCH(n) == 1) {
  1562.         n = CHILD(n, 0);
  1563.         switch (TYPE(n)) {
  1564.         case LESS:    return LT;
  1565.         case GREATER:    return GT;
  1566.         case EQEQUAL:            /* == */
  1567.         case EQUAL:    return EQ;
  1568.         case LESSEQUAL:    return LE;
  1569.         case GREATEREQUAL: return GE;
  1570.         case NOTEQUAL:    return NE;    /* <> or != */
  1571.         case NAME:    if (strcmp(STR(n), "in") == 0) return IN;
  1572.                 if (strcmp(STR(n), "is") == 0) return IS;
  1573.         }
  1574.     }
  1575.     else if (NCH(n) == 2) {
  1576.         switch (TYPE(CHILD(n, 0))) {
  1577.         case NAME:    if (strcmp(STR(CHILD(n, 1)), "in") == 0)
  1578.                     return NOT_IN;
  1579.                 if (strcmp(STR(CHILD(n, 0)), "is") == 0)
  1580.                     return IS_NOT;
  1581.         }
  1582.     }
  1583.     return BAD;
  1584. }
  1585.  
  1586. static void
  1587. com_comparison(c, n)
  1588.     struct compiling *c;
  1589.     node *n;
  1590. {
  1591.     int i;
  1592.     enum cmp_op op;
  1593.     int anchor;
  1594.     REQ(n, comparison); /* comparison: expr (comp_op expr)* */
  1595.     com_expr(c, CHILD(n, 0));
  1596.     if (NCH(n) == 1)
  1597.         return;
  1598.     
  1599.     /****************************************************************
  1600.        The following code is generated for all but the last
  1601.        comparison in a chain:
  1602.        
  1603.        label:    on stack:    opcode:        jump to:
  1604.        
  1605.             a        <code to load b>
  1606.             a, b        DUP_TOP
  1607.             a, b, b        ROT_THREE
  1608.             b, a, b        COMPARE_OP
  1609.             b, 0-or-1    JUMP_IF_FALSE    L1
  1610.             b, 1        POP_TOP
  1611.             b        
  1612.     
  1613.        We are now ready to repeat this sequence for the next
  1614.        comparison in the chain.
  1615.        
  1616.        For the last we generate:
  1617.        
  1618.                b        <code to load c>
  1619.                b, c        COMPARE_OP
  1620.                0-or-1        
  1621.        
  1622.        If there were any jumps to L1 (i.e., there was more than one
  1623.        comparison), we generate:
  1624.        
  1625.                0-or-1        JUMP_FORWARD    L2
  1626.        L1:        b, 0        ROT_TWO
  1627.                0, b        POP_TOP
  1628.                0
  1629.        L2:        0-or-1
  1630.     ****************************************************************/
  1631.     
  1632.     anchor = 0;
  1633.     
  1634.     for (i = 2; i < NCH(n); i += 2) {
  1635.         com_expr(c, CHILD(n, i));
  1636.         if (i+2 < NCH(n)) {
  1637.             com_addbyte(c, DUP_TOP);
  1638.             com_push(c, 1);
  1639.             com_addbyte(c, ROT_THREE);
  1640.         }
  1641.         op = cmp_type(CHILD(n, i-1));
  1642.         if (op == BAD) {
  1643.             com_error(c, PyExc_SystemError,
  1644.                   "com_comparison: unknown comparison op");
  1645.         }
  1646.         com_addoparg(c, COMPARE_OP, op);
  1647.         com_pop(c, 1);
  1648.         if (i+2 < NCH(n)) {
  1649.             com_addfwref(c, JUMP_IF_FALSE, &anchor);
  1650.             com_addbyte(c, POP_TOP);
  1651.             com_pop(c, 1);
  1652.         }
  1653.     }
  1654.     
  1655.     if (anchor) {
  1656.         int anchor2 = 0;
  1657.         com_addfwref(c, JUMP_FORWARD, &anchor2);
  1658.         com_backpatch(c, anchor);
  1659.         com_addbyte(c, ROT_TWO);
  1660.         com_addbyte(c, POP_TOP);
  1661.         com_backpatch(c, anchor2);
  1662.     }
  1663. }
  1664.  
  1665. static void
  1666. com_not_test(c, n)
  1667.     struct compiling *c;
  1668.     node *n;
  1669. {
  1670.     REQ(n, not_test); /* 'not' not_test | comparison */
  1671.     if (NCH(n) == 1) {
  1672.         com_comparison(c, CHILD(n, 0));
  1673.     }
  1674.     else {
  1675.         com_not_test(c, CHILD(n, 1));
  1676.         com_addbyte(c, UNARY_NOT);
  1677.     }
  1678. }
  1679.  
  1680. static void
  1681. com_and_test(c, n)
  1682.     struct compiling *c;
  1683.     node *n;
  1684. {
  1685.     int i;
  1686.     int anchor;
  1687.     REQ(n, and_test); /* not_test ('and' not_test)* */
  1688.     anchor = 0;
  1689.     i = 0;
  1690.     for (;;) {
  1691.         com_not_test(c, CHILD(n, i));
  1692.         if ((i += 2) >= NCH(n))
  1693.             break;
  1694.         com_addfwref(c, JUMP_IF_FALSE, &anchor);
  1695.         com_addbyte(c, POP_TOP);
  1696.         com_pop(c, 1);
  1697.     }
  1698.     if (anchor)
  1699.         com_backpatch(c, anchor);
  1700. }
  1701.  
  1702. static void
  1703. com_test(c, n)
  1704.     struct compiling *c;
  1705.     node *n;
  1706. {
  1707.     REQ(n, test); /* and_test ('or' and_test)* | lambdef */
  1708.     if (NCH(n) == 1 && TYPE(CHILD(n, 0)) == lambdef) {
  1709.         PyObject *v;
  1710.         int i;
  1711.         int ndefs = com_argdefs(c, CHILD(n, 0));
  1712.         v = (PyObject *) icompile(CHILD(n, 0), c);
  1713.         if (v == NULL) {
  1714.             c->c_errors++;
  1715.             i = 255;
  1716.         }
  1717.         else {
  1718.             i = com_addconst(c, v);
  1719.             Py_DECREF(v);
  1720.         }
  1721.         com_addoparg(c, LOAD_CONST, i);
  1722.         com_push(c, 1);
  1723.         com_addoparg(c, MAKE_FUNCTION, ndefs);
  1724.         com_pop(c, ndefs);
  1725.     }
  1726.     else {
  1727.         int anchor = 0;
  1728.         int i = 0;
  1729.         for (;;) {
  1730.             com_and_test(c, CHILD(n, i));
  1731.             if ((i += 2) >= NCH(n))
  1732.                 break;
  1733.             com_addfwref(c, JUMP_IF_TRUE, &anchor);
  1734.             com_addbyte(c, POP_TOP);
  1735.             com_pop(c, 1);
  1736.         }
  1737.         if (anchor)
  1738.             com_backpatch(c, anchor);
  1739.     }
  1740. }
  1741.  
  1742. static void
  1743. com_list(c, n, toplevel)
  1744.     struct compiling *c;
  1745.     node *n;
  1746.     int toplevel; /* If nonzero, *always* build a tuple */
  1747. {
  1748.     /* exprlist: expr (',' expr)* [',']; likewise for testlist */
  1749.     if (NCH(n) == 1 && !toplevel) {
  1750.         com_node(c, CHILD(n, 0));
  1751.     }
  1752.     else {
  1753.         int i;
  1754.         int len;
  1755.         len = (NCH(n) + 1) / 2;
  1756.         for (i = 0; i < NCH(n); i += 2)
  1757.             com_node(c, CHILD(n, i));
  1758.         com_addoparg(c, BUILD_TUPLE, len);
  1759.         com_pop(c, len-1);
  1760.     }
  1761. }
  1762.  
  1763.  
  1764. /* Begin of assignment compilation */
  1765.  
  1766. static void com_assign_name Py_PROTO((struct compiling *, node *, int));
  1767. static void com_assign Py_PROTO((struct compiling *, node *, int));
  1768.  
  1769. static void
  1770. com_assign_attr(c, n, assigning)
  1771.     struct compiling *c;
  1772.     node *n;
  1773.     int assigning;
  1774. {
  1775.     com_addopname(c, assigning ? STORE_ATTR : DELETE_ATTR, n);
  1776.     com_pop(c, assigning ? 2 : 1);
  1777. }
  1778.  
  1779. static void
  1780. com_assign_trailer(c, n, assigning)
  1781.     struct compiling *c;
  1782.     node *n;
  1783.     int assigning;
  1784. {
  1785.     REQ(n, trailer);
  1786.     switch (TYPE(CHILD(n, 0))) {
  1787.     case LPAR: /* '(' [exprlist] ')' */
  1788.         com_error(c, PyExc_SyntaxError,
  1789.               "can't assign to function call");
  1790.         break;
  1791.     case DOT: /* '.' NAME */
  1792.         com_assign_attr(c, CHILD(n, 1), assigning);
  1793.         break;
  1794.     case LSQB: /* '[' subscriptlist ']' */
  1795.         com_subscriptlist(c, CHILD(n, 1), assigning);
  1796.         break;
  1797.     default:
  1798.         com_error(c, PyExc_SystemError, "unknown trailer type");
  1799.     }
  1800. }
  1801.  
  1802. static void
  1803. com_assign_tuple(c, n, assigning)
  1804.     struct compiling *c;
  1805.     node *n;
  1806.     int assigning;
  1807. {
  1808.     int i;
  1809.     if (TYPE(n) != testlist)
  1810.         REQ(n, exprlist);
  1811.     if (assigning) {
  1812.         i = (NCH(n)+1)/2;
  1813.         com_addoparg(c, UNPACK_TUPLE, i);
  1814.         com_push(c, i-1);
  1815.     }
  1816.     for (i = 0; i < NCH(n); i += 2)
  1817.         com_assign(c, CHILD(n, i), assigning);
  1818. }
  1819.  
  1820. static void
  1821. com_assign_list(c, n, assigning)
  1822.     struct compiling *c;
  1823.     node *n;
  1824.     int assigning;
  1825. {
  1826.     int i;
  1827.     if (assigning) {
  1828.         i = (NCH(n)+1)/2;
  1829.         com_addoparg(c, UNPACK_LIST, i);
  1830.         com_push(c, i-1);
  1831.     }
  1832.     for (i = 0; i < NCH(n); i += 2)
  1833.         com_assign(c, CHILD(n, i), assigning);
  1834. }
  1835.  
  1836. static void
  1837. com_assign_name(c, n, assigning)
  1838.     struct compiling *c;
  1839.     node *n;
  1840.     int assigning;
  1841. {
  1842.     REQ(n, NAME);
  1843.     com_addopname(c, assigning ? STORE_NAME : DELETE_NAME, n);
  1844.     if (assigning)
  1845.         com_pop(c, 1);
  1846. }
  1847.  
  1848. static void
  1849. com_assign(c, n, assigning)
  1850.     struct compiling *c;
  1851.     node *n;
  1852.     int assigning;
  1853. {
  1854.     /* Loop to avoid trivial recursion */
  1855.     for (;;) {
  1856.         switch (TYPE(n)) {
  1857.         
  1858.         case exprlist:
  1859.         case testlist:
  1860.             if (NCH(n) > 1) {
  1861.                 com_assign_tuple(c, n, assigning);
  1862.                 return;
  1863.             }
  1864.             n = CHILD(n, 0);
  1865.             break;
  1866.         
  1867.         case test:
  1868.         case and_test:
  1869.         case not_test:
  1870.         case comparison:
  1871.         case expr:
  1872.         case xor_expr:
  1873.         case and_expr:
  1874.         case shift_expr:
  1875.         case arith_expr:
  1876.         case term:
  1877.         case factor:
  1878.             if (NCH(n) > 1) {
  1879.                 com_error(c, PyExc_SyntaxError,
  1880.                       "can't assign to operator");
  1881.                 return;
  1882.             }
  1883.             n = CHILD(n, 0);
  1884.             break;
  1885.         
  1886.         case power: /* atom trailer* ('**' power)* */
  1887. /* ('+'|'-'|'~') factor | atom trailer* */
  1888.             if (TYPE(CHILD(n, 0)) != atom) {
  1889.                 com_error(c, PyExc_SyntaxError,
  1890.                       "can't assign to operator");
  1891.                 return;
  1892.             }
  1893.             if (NCH(n) > 1) { /* trailer or exponent present */
  1894.                 int i;
  1895.                 com_node(c, CHILD(n, 0));
  1896.                 for (i = 1; i+1 < NCH(n); i++) {
  1897.                     if (TYPE(CHILD(n, i)) == DOUBLESTAR) {
  1898.                         com_error(c, PyExc_SyntaxError,
  1899.                           "can't assign to operator");
  1900.                         return;
  1901.                     }
  1902.                     com_apply_trailer(c, CHILD(n, i));
  1903.                 } /* NB i is still alive */
  1904.                 com_assign_trailer(c,
  1905.                         CHILD(n, i), assigning);
  1906.                 return;
  1907.             }
  1908.             n = CHILD(n, 0);
  1909.             break;
  1910.         
  1911.         case atom:
  1912.             switch (TYPE(CHILD(n, 0))) {
  1913.             case LPAR:
  1914.                 n = CHILD(n, 1);
  1915.                 if (TYPE(n) == RPAR) {
  1916.                     /* XXX Should allow () = () ??? */
  1917.                     com_error(c, PyExc_SyntaxError,
  1918.                           "can't assign to ()");
  1919.                     return;
  1920.                 }
  1921.                 break;
  1922.             case LSQB:
  1923.                 n = CHILD(n, 1);
  1924.                 if (TYPE(n) == RSQB) {
  1925.                     com_error(c, PyExc_SyntaxError,
  1926.                           "can't assign to []");
  1927.                     return;
  1928.                 }
  1929.                 com_assign_list(c, n, assigning);
  1930.                 return;
  1931.             case NAME:
  1932.                 com_assign_name(c, CHILD(n, 0), assigning);
  1933.                 return;
  1934.             default:
  1935.                 com_error(c, PyExc_SyntaxError,
  1936.                       "can't assign to literal");
  1937.                 return;
  1938.             }
  1939.             break;
  1940.  
  1941.         case lambdef:
  1942.             com_error(c, PyExc_SyntaxError,
  1943.                   "can't assign to lambda");
  1944.             return;
  1945.         
  1946.         default:
  1947.             /* XXX fprintf(stderr, "node type %d\n", TYPE(n)); */
  1948.             com_error(c, PyExc_SystemError,
  1949.                   "com_assign: bad node");
  1950.             return;
  1951.         
  1952.         }
  1953.     }
  1954. }
  1955.  
  1956. /* Forward */ static node *get_rawdocstring Py_PROTO((node *));
  1957.  
  1958. static void
  1959. com_expr_stmt(c, n)
  1960.     struct compiling *c;
  1961.     node *n;
  1962. {
  1963.     REQ(n, expr_stmt); /* testlist ('=' testlist)* */
  1964.     /* Forget it if we have just a doc string here */
  1965.     if (!c->c_interactive && NCH(n) == 1 && get_rawdocstring(n) != NULL)
  1966.         return;
  1967.     com_node(c, CHILD(n, NCH(n)-1));
  1968.     if (NCH(n) == 1) {
  1969.         if (c->c_interactive)
  1970.             com_addbyte(c, PRINT_EXPR);
  1971.         else
  1972.             com_addbyte(c, POP_TOP);
  1973.         com_pop(c, 1);
  1974.     }
  1975.     else {
  1976.         int i;
  1977.         for (i = 0; i < NCH(n)-2; i+=2) {
  1978.             if (i+2 < NCH(n)-2) {
  1979.                 com_addbyte(c, DUP_TOP);
  1980.                 com_push(c, 1);
  1981.             }
  1982.             com_assign(c, CHILD(n, i), OP_ASSIGN);
  1983.         }
  1984.     }
  1985. }
  1986.  
  1987. static void
  1988. com_assert_stmt(c, n)
  1989.     struct compiling *c;
  1990.     node *n;
  1991. {
  1992.     int a = 0, b = 0;
  1993.     int i;
  1994.     REQ(n, assert_stmt); /* 'assert' test [',' test] */
  1995.     /* Generate code like for
  1996.        
  1997.        if __debug__:
  1998.           if not <test>:
  1999.              raise AssertionError [, <message>]
  2000.  
  2001.        where <message> is the second test, if present.
  2002.     */
  2003.     if (Py_OptimizeFlag)
  2004.         return;
  2005.     com_addopnamestr(c, LOAD_GLOBAL, "__debug__");
  2006.     com_push(c, 1);
  2007.     com_addfwref(c, JUMP_IF_FALSE, &a);
  2008.     com_addbyte(c, POP_TOP);
  2009.     com_pop(c, 1);
  2010.     com_node(c, CHILD(n, 1));
  2011.     com_addfwref(c, JUMP_IF_TRUE, &b);
  2012.     com_addbyte(c, POP_TOP);
  2013.     com_pop(c, 1);
  2014.     /* Raise that exception! */
  2015.     com_addopnamestr(c, LOAD_GLOBAL, "AssertionError");
  2016.     com_push(c, 1);
  2017.     i = NCH(n)/2; /* Either 2 or 4 */
  2018.     if (i > 1)
  2019.         com_node(c, CHILD(n, 3));
  2020.     com_addoparg(c, RAISE_VARARGS, i);
  2021.     com_pop(c, i);
  2022.     /* The interpreter does not fall through */
  2023.     /* All jumps converge here */
  2024.     com_backpatch(c, a);
  2025.     com_backpatch(c, b);
  2026.     com_addbyte(c, POP_TOP);
  2027. }
  2028.  
  2029. static void
  2030. com_print_stmt(c, n)
  2031.     struct compiling *c;
  2032.     node *n;
  2033. {
  2034.     int i;
  2035.     REQ(n, print_stmt); /* 'print' (test ',')* [test] */
  2036.     for (i = 1; i < NCH(n); i += 2) {
  2037.         com_node(c, CHILD(n, i));
  2038.         com_addbyte(c, PRINT_ITEM);
  2039.         com_pop(c, 1);
  2040.     }
  2041.     if (TYPE(CHILD(n, NCH(n)-1)) != COMMA)
  2042.         com_addbyte(c, PRINT_NEWLINE);
  2043.         /* XXX Alternatively, LOAD_CONST '\n' and then PRINT_ITEM */
  2044. }
  2045.  
  2046. static void
  2047. com_return_stmt(c, n)
  2048.     struct compiling *c;
  2049.     node *n;
  2050. {
  2051.     REQ(n, return_stmt); /* 'return' [testlist] */
  2052.     if (!c->c_infunction) {
  2053.         com_error(c, PyExc_SyntaxError, "'return' outside function");
  2054.     }
  2055.     if (NCH(n) < 2) {
  2056.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  2057.         com_push(c, 1);
  2058.     }
  2059.     else
  2060.         com_node(c, CHILD(n, 1));
  2061.     com_addbyte(c, RETURN_VALUE);
  2062.     com_pop(c, 1);
  2063. }
  2064.  
  2065. static void
  2066. com_raise_stmt(c, n)
  2067.     struct compiling *c;
  2068.     node *n;
  2069. {
  2070.     int i;
  2071.     REQ(n, raise_stmt); /* 'raise' [test [',' test [',' test]]] */
  2072.     if (NCH(n) > 1) {
  2073.         com_node(c, CHILD(n, 1));
  2074.         if (NCH(n) > 3) {
  2075.             com_node(c, CHILD(n, 3));
  2076.             if (NCH(n) > 5)
  2077.                 com_node(c, CHILD(n, 5));
  2078.         }
  2079.     }
  2080.     i = NCH(n)/2;
  2081.     com_addoparg(c, RAISE_VARARGS, i);
  2082.     com_pop(c, i);
  2083. }
  2084.  
  2085. static void
  2086. com_import_stmt(c, n)
  2087.     struct compiling *c;
  2088.     node *n;
  2089. {
  2090.     int i;
  2091.     REQ(n, import_stmt);
  2092.     /* 'import' dotted_name (',' dotted_name)* |
  2093.        'from' dotted_name 'import' ('*' | NAME (',' NAME)*) */
  2094.     if (STR(CHILD(n, 0))[0] == 'f') {
  2095.         /* 'from' dotted_name 'import' ... */
  2096.         REQ(CHILD(n, 1), dotted_name);
  2097.         com_addopname(c, IMPORT_NAME, CHILD(n, 1));
  2098.         com_push(c, 1);
  2099.         for (i = 3; i < NCH(n); i += 2)
  2100.             com_addopname(c, IMPORT_FROM, CHILD(n, i));
  2101.         com_addbyte(c, POP_TOP);
  2102.         com_pop(c, 1);
  2103.     }
  2104.     else {
  2105.         /* 'import' ... */
  2106.         for (i = 1; i < NCH(n); i += 2) {
  2107.             REQ(CHILD(n, i), dotted_name);
  2108.             com_addopname(c, IMPORT_NAME, CHILD(n, i));
  2109.             com_push(c, 1);
  2110.             com_addopname(c, STORE_NAME, CHILD(CHILD(n, i), 0));
  2111.             com_pop(c, 1);
  2112.         }
  2113.     }
  2114. }
  2115.  
  2116. static void
  2117. com_global_stmt(c, n)
  2118.     struct compiling *c;
  2119.     node *n;
  2120. {
  2121.     int i;
  2122.     REQ(n, global_stmt);
  2123.     /* 'global' NAME (',' NAME)* */
  2124.     for (i = 1; i < NCH(n); i += 2) {
  2125.         char *s = STR(CHILD(n, i));
  2126. #ifdef PRIVATE_NAME_MANGLING
  2127.         char buffer[256];
  2128.         if (s != NULL && s[0] == '_' && s[1] == '_' &&
  2129.             c->c_private != NULL &&
  2130.             com_mangle(c, s, buffer, (int)sizeof(buffer)))
  2131.             s = buffer;
  2132. #endif
  2133.         if (PyDict_GetItemString(c->c_locals, s) != NULL) {
  2134.             com_error(c, PyExc_SyntaxError,
  2135.                   "name is local and global");
  2136.         }
  2137.         else if (PyDict_SetItemString(c->c_globals, s, Py_None) != 0)
  2138.             c->c_errors++;
  2139.     }
  2140. }
  2141.  
  2142. static int
  2143. com_newlocal_o(c, nameval)
  2144.     struct compiling *c;
  2145.     PyObject *nameval;
  2146. {
  2147.     int i;
  2148.     PyObject *ival;
  2149.     if (PyList_Size(c->c_varnames) != c->c_nlocals) {
  2150.         /* This is usually caused by an error on a previous call */
  2151.         if (c->c_errors == 0) {
  2152.             com_error(c, PyExc_SystemError,
  2153.                   "mixed up var name/index");
  2154.         }
  2155.         return 0;
  2156.     }
  2157.     ival = PyInt_FromLong(i = c->c_nlocals++);
  2158.     if (ival == NULL)
  2159.         c->c_errors++;
  2160.     else if (PyDict_SetItem(c->c_locals, nameval, ival) != 0)
  2161.         c->c_errors++;
  2162.     else if (PyList_Append(c->c_varnames, nameval) != 0)
  2163.         c->c_errors++;
  2164.     Py_XDECREF(ival);
  2165.     return i;
  2166. }
  2167.  
  2168. static int
  2169. com_addlocal_o(c, nameval)
  2170.     struct compiling *c;
  2171.     PyObject *nameval;
  2172. {
  2173.     PyObject *ival =  PyDict_GetItem(c->c_locals, nameval);
  2174.     if (ival != NULL)
  2175.         return PyInt_AsLong(ival);
  2176.     return com_newlocal_o(c, nameval);
  2177. }
  2178.  
  2179. static int
  2180. com_newlocal(c, name)
  2181.     struct compiling *c;
  2182.     char *name;
  2183. {
  2184.     PyObject *nameval = PyString_InternFromString(name);
  2185.     int i;
  2186.     if (nameval == NULL) {
  2187.         c->c_errors++;
  2188.         return 0;
  2189.     }
  2190.     i = com_newlocal_o(c, nameval);
  2191.     Py_DECREF(nameval);
  2192.     return i;
  2193. }
  2194.  
  2195. static void
  2196. com_exec_stmt(c, n)
  2197.     struct compiling *c;
  2198.     node *n;
  2199. {
  2200.     REQ(n, exec_stmt);
  2201.     /* exec_stmt: 'exec' expr ['in' expr [',' expr]] */
  2202.     com_node(c, CHILD(n, 1));
  2203.     if (NCH(n) >= 4)
  2204.         com_node(c, CHILD(n, 3));
  2205.     else {
  2206.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  2207.         com_push(c, 1);
  2208.     }
  2209.     if (NCH(n) >= 6)
  2210.         com_node(c, CHILD(n, 5));
  2211.     else {
  2212.         com_addbyte(c, DUP_TOP);
  2213.         com_push(c, 1);
  2214.     }
  2215.     com_addbyte(c, EXEC_STMT);
  2216.     com_pop(c, 3);
  2217. }
  2218.  
  2219. static int
  2220. is_constant_false(c, n)
  2221.     struct compiling *c;
  2222.     node *n;
  2223. {
  2224.     PyObject *v;
  2225.     int i;
  2226.  
  2227.   /* Label to avoid tail recursion */
  2228.   next:
  2229.     switch (TYPE(n)) {
  2230.  
  2231.     case suite:
  2232.         if (NCH(n) == 1) {
  2233.             n = CHILD(n, 0);
  2234.             goto next;
  2235.         }
  2236.         /* Fall through */
  2237.     case file_input:
  2238.         for (i = 0; i < NCH(n); i++) {
  2239.             node *ch = CHILD(n, i);
  2240.             if (TYPE(ch) == stmt) {
  2241.                 n = ch;
  2242.                 goto next;
  2243.             }
  2244.         }
  2245.         break;
  2246.  
  2247.     case stmt:
  2248.     case simple_stmt:
  2249.     case small_stmt:
  2250.         n = CHILD(n, 0);
  2251.         goto next;
  2252.  
  2253.     case expr_stmt:
  2254.     case testlist:
  2255.     case test:
  2256.     case and_test:
  2257.     case not_test:
  2258.     case comparison:
  2259.     case expr:
  2260.     case xor_expr:
  2261.     case and_expr:
  2262.     case shift_expr:
  2263.     case arith_expr:
  2264.     case term:
  2265.     case factor:
  2266.     case power:
  2267.     case atom:
  2268.         if (NCH(n) == 1) {
  2269.             n = CHILD(n, 0);
  2270.             goto next;
  2271.         }
  2272.         break;
  2273.  
  2274.     case NAME:
  2275.         if (Py_OptimizeFlag && strcmp(STR(n), "__debug__") == 0)
  2276.             return 1;
  2277.         break;
  2278.  
  2279.     case NUMBER:
  2280.         v = parsenumber(c, STR(n));
  2281.         if (v == NULL) {
  2282.             PyErr_Clear();
  2283.             break;
  2284.         }
  2285.         i = PyObject_IsTrue(v);
  2286.         Py_DECREF(v);
  2287.         return i == 0;
  2288.  
  2289.     case STRING:
  2290.         v = parsestr(STR(n));
  2291.         if (v == NULL) {
  2292.             PyErr_Clear();
  2293.             break;
  2294.         }
  2295.         i = PyObject_IsTrue(v);
  2296.         Py_DECREF(v);
  2297.         return i == 0;
  2298.  
  2299.     }
  2300.     return 0;
  2301. }
  2302.  
  2303. static void
  2304. com_if_stmt(c, n)
  2305.     struct compiling *c;
  2306.     node *n;
  2307. {
  2308.     int i;
  2309.     int anchor = 0;
  2310.     REQ(n, if_stmt);
  2311.     /*'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] */
  2312.     for (i = 0; i+3 < NCH(n); i+=4) {
  2313.         int a = 0;
  2314.         node *ch = CHILD(n, i+1);
  2315.         if (is_constant_false(c, ch))
  2316.             continue;
  2317.         if (i > 0)
  2318.             com_addoparg(c, SET_LINENO, ch->n_lineno);
  2319.         com_node(c, ch);
  2320.         com_addfwref(c, JUMP_IF_FALSE, &a);
  2321.         com_addbyte(c, POP_TOP);
  2322.         com_pop(c, 1);
  2323.         com_node(c, CHILD(n, i+3));
  2324.         com_addfwref(c, JUMP_FORWARD, &anchor);
  2325.         com_backpatch(c, a);
  2326.         /* We jump here with an extra entry which we now pop */
  2327.         com_addbyte(c, POP_TOP);
  2328.     }
  2329.     if (i+2 < NCH(n))
  2330.         com_node(c, CHILD(n, i+2));
  2331.     if (anchor)
  2332.         com_backpatch(c, anchor);
  2333. }
  2334.  
  2335. static void
  2336. com_while_stmt(c, n)
  2337.     struct compiling *c;
  2338.     node *n;
  2339. {
  2340.     int break_anchor = 0;
  2341.     int anchor = 0;
  2342.     int save_begin = c->c_begin;
  2343.     REQ(n, while_stmt); /* 'while' test ':' suite ['else' ':' suite] */
  2344.     com_addfwref(c, SETUP_LOOP, &break_anchor);
  2345.     block_push(c, SETUP_LOOP);
  2346.     c->c_begin = c->c_nexti;
  2347.     com_addoparg(c, SET_LINENO, n->n_lineno);
  2348.     com_node(c, CHILD(n, 1));
  2349.     com_addfwref(c, JUMP_IF_FALSE, &anchor);
  2350.     com_addbyte(c, POP_TOP);
  2351.     com_pop(c, 1);
  2352.     c->c_loops++;
  2353.     com_node(c, CHILD(n, 3));
  2354.     c->c_loops--;
  2355.     com_addoparg(c, JUMP_ABSOLUTE, c->c_begin);
  2356.     c->c_begin = save_begin;
  2357.     com_backpatch(c, anchor);
  2358.     /* We jump here with one entry more on the stack */
  2359.     com_addbyte(c, POP_TOP);
  2360.     com_addbyte(c, POP_BLOCK);
  2361.     block_pop(c, SETUP_LOOP);
  2362.     if (NCH(n) > 4)
  2363.         com_node(c, CHILD(n, 6));
  2364.     com_backpatch(c, break_anchor);
  2365. }
  2366.  
  2367. static void
  2368. com_for_stmt(c, n)
  2369.     struct compiling *c;
  2370.     node *n;
  2371. {
  2372.     PyObject *v;
  2373.     int break_anchor = 0;
  2374.     int anchor = 0;
  2375.     int save_begin = c->c_begin;
  2376.     REQ(n, for_stmt);
  2377.     /* 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] */
  2378.     com_addfwref(c, SETUP_LOOP, &break_anchor);
  2379.     block_push(c, SETUP_LOOP);
  2380.     com_node(c, CHILD(n, 3));
  2381.     v = PyInt_FromLong(0L);
  2382.     if (v == NULL)
  2383.         c->c_errors++;
  2384.     com_addoparg(c, LOAD_CONST, com_addconst(c, v));
  2385.     com_push(c, 1);
  2386.     Py_XDECREF(v);
  2387.     c->c_begin = c->c_nexti;
  2388.     com_addoparg(c, SET_LINENO, n->n_lineno);
  2389.     com_addfwref(c, FOR_LOOP, &anchor);
  2390.     com_push(c, 1);
  2391.     com_assign(c, CHILD(n, 1), OP_ASSIGN);
  2392.     c->c_loops++;
  2393.     com_node(c, CHILD(n, 5));
  2394.     c->c_loops--;
  2395.     com_addoparg(c, JUMP_ABSOLUTE, c->c_begin);
  2396.     c->c_begin = save_begin;
  2397.     com_backpatch(c, anchor);
  2398.     com_pop(c, 2); /* FOR_LOOP has popped these */
  2399.     com_addbyte(c, POP_BLOCK);
  2400.     block_pop(c, SETUP_LOOP);
  2401.     if (NCH(n) > 8)
  2402.         com_node(c, CHILD(n, 8));
  2403.     com_backpatch(c, break_anchor);
  2404. }
  2405.  
  2406. /* Code generated for "try: S finally: Sf" is as follows:
  2407.    
  2408.         SETUP_FINALLY    L
  2409.         <code for S>
  2410.         POP_BLOCK
  2411.         LOAD_CONST    <nil>
  2412.     L:    <code for Sf>
  2413.         END_FINALLY
  2414.    
  2415.    The special instructions use the block stack.  Each block
  2416.    stack entry contains the instruction that created it (here
  2417.    SETUP_FINALLY), the level of the value stack at the time the
  2418.    block stack entry was created, and a label (here L).
  2419.    
  2420.    SETUP_FINALLY:
  2421.     Pushes the current value stack level and the label
  2422.     onto the block stack.
  2423.    POP_BLOCK:
  2424.     Pops en entry from the block stack, and pops the value
  2425.     stack until its level is the same as indicated on the
  2426.     block stack.  (The label is ignored.)
  2427.    END_FINALLY:
  2428.     Pops a variable number of entries from the *value* stack
  2429.     and re-raises the exception they specify.  The number of
  2430.     entries popped depends on the (pseudo) exception type.
  2431.    
  2432.    The block stack is unwound when an exception is raised:
  2433.    when a SETUP_FINALLY entry is found, the exception is pushed
  2434.    onto the value stack (and the exception condition is cleared),
  2435.    and the interpreter jumps to the label gotten from the block
  2436.    stack.
  2437.    
  2438.    Code generated for "try: S except E1, V1: S1 except E2, V2: S2 ...":
  2439.    (The contents of the value stack is shown in [], with the top
  2440.    at the right; 'tb' is trace-back info, 'val' the exception's
  2441.    associated value, and 'exc' the exception.)
  2442.    
  2443.    Value stack        Label    Instruction    Argument
  2444.    []                SETUP_EXCEPT    L1
  2445.    []                <code for S>
  2446.    []                POP_BLOCK
  2447.    []                JUMP_FORWARD    L0
  2448.    
  2449.    [tb, val, exc]    L1:    DUP                )
  2450.    [tb, val, exc, exc]        <evaluate E1>            )
  2451.    [tb, val, exc, exc, E1]    COMPARE_OP    EXC_MATCH    ) only if E1
  2452.    [tb, val, exc, 1-or-0]    JUMP_IF_FALSE    L2        )
  2453.    [tb, val, exc, 1]        POP                )
  2454.    [tb, val, exc]        POP
  2455.    [tb, val]            <assign to V1>    (or POP if no V1)
  2456.    [tb]                POP
  2457.    []                <code for S1>
  2458.                    JUMP_FORWARD    L0
  2459.    
  2460.    [tb, val, exc, 0]    L2:    POP
  2461.    [tb, val, exc]        DUP
  2462.    .............................etc.......................
  2463.  
  2464.    [tb, val, exc, 0]    Ln+1:    POP
  2465.    [tb, val, exc]           END_FINALLY    # re-raise exception
  2466.    
  2467.    []            L0:    <next statement>
  2468.    
  2469.    Of course, parts are not generated if Vi or Ei is not present.
  2470. */
  2471.  
  2472. static void
  2473. com_try_except(c, n)
  2474.     struct compiling *c;
  2475.     node *n;
  2476. {
  2477.     int except_anchor = 0;
  2478.     int end_anchor = 0;
  2479.     int else_anchor = 0;
  2480.     int i;
  2481.     node *ch;
  2482.  
  2483.     com_addfwref(c, SETUP_EXCEPT, &except_anchor);
  2484.     block_push(c, SETUP_EXCEPT);
  2485.     com_node(c, CHILD(n, 2));
  2486.     com_addbyte(c, POP_BLOCK);
  2487.     block_pop(c, SETUP_EXCEPT);
  2488.     com_addfwref(c, JUMP_FORWARD, &else_anchor);
  2489.     com_backpatch(c, except_anchor);
  2490.     for (i = 3;
  2491.          i < NCH(n) && TYPE(ch = CHILD(n, i)) == except_clause;
  2492.          i += 3) {
  2493.         /* except_clause: 'except' [expr [',' var]] */
  2494.         if (except_anchor == 0) {
  2495.             com_error(c, PyExc_SyntaxError,
  2496.                   "default 'except:' must be last");
  2497.             break;
  2498.         }
  2499.         except_anchor = 0;
  2500.         com_push(c, 3); /* tb, val, exc pushed by exception */
  2501.         com_addoparg(c, SET_LINENO, ch->n_lineno);
  2502.         if (NCH(ch) > 1) {
  2503.             com_addbyte(c, DUP_TOP);
  2504.             com_push(c, 1);
  2505.             com_node(c, CHILD(ch, 1));
  2506.             com_addoparg(c, COMPARE_OP, EXC_MATCH);
  2507.             com_pop(c, 1);
  2508.             com_addfwref(c, JUMP_IF_FALSE, &except_anchor);
  2509.             com_addbyte(c, POP_TOP);
  2510.             com_pop(c, 1);
  2511.         }
  2512.         com_addbyte(c, POP_TOP);
  2513.         com_pop(c, 1);
  2514.         if (NCH(ch) > 3)
  2515.             com_assign(c, CHILD(ch, 3), OP_ASSIGN);
  2516.         else {
  2517.             com_addbyte(c, POP_TOP);
  2518.             com_pop(c, 1);
  2519.         }
  2520.         com_addbyte(c, POP_TOP);
  2521.         com_pop(c, 1);
  2522.         com_node(c, CHILD(n, i+2));
  2523.         com_addfwref(c, JUMP_FORWARD, &end_anchor);
  2524.         if (except_anchor) {
  2525.             com_backpatch(c, except_anchor);
  2526.             /* We come in with [tb, val, exc, 0] on the
  2527.                stack; one pop and it's the same as
  2528.                expected at the start of the loop */
  2529.             com_addbyte(c, POP_TOP);
  2530.         }
  2531.     }
  2532.     /* We actually come in here with [tb, val, exc] but the
  2533.        END_FINALLY will zap those and jump around.
  2534.        The c_stacklevel does not reflect them so we need not pop
  2535.        anything. */
  2536.     com_addbyte(c, END_FINALLY);
  2537.     com_backpatch(c, else_anchor);
  2538.     if (i < NCH(n))
  2539.         com_node(c, CHILD(n, i+2));
  2540.     com_backpatch(c, end_anchor);
  2541. }
  2542.  
  2543. static void
  2544. com_try_finally(c, n)
  2545.     struct compiling *c;
  2546.     node *n;
  2547. {
  2548.     int finally_anchor = 0;
  2549.     node *ch;
  2550.  
  2551.     com_addfwref(c, SETUP_FINALLY, &finally_anchor);
  2552.     block_push(c, SETUP_FINALLY);
  2553.     com_node(c, CHILD(n, 2));
  2554.     com_addbyte(c, POP_BLOCK);
  2555.     block_pop(c, SETUP_FINALLY);
  2556.     block_push(c, END_FINALLY);
  2557.     com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  2558.     /* While the generated code pushes only one item,
  2559.        the try-finally handling can enter here with
  2560.        up to three items.  OK, here are the details:
  2561.        3 for an exception, 2 for RETURN, 1 for BREAK. */
  2562.     com_push(c, 3);
  2563.     com_backpatch(c, finally_anchor);
  2564.     ch = CHILD(n, NCH(n)-1);
  2565.     com_addoparg(c, SET_LINENO, ch->n_lineno);
  2566.     com_node(c, ch);
  2567.     com_addbyte(c, END_FINALLY);
  2568.     block_pop(c, END_FINALLY);
  2569.     com_pop(c, 3); /* Matches the com_push above */
  2570. }
  2571.  
  2572. static void
  2573. com_try_stmt(c, n)
  2574.     struct compiling *c;
  2575.     node *n;
  2576. {
  2577.     REQ(n, try_stmt);
  2578.     /* 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
  2579.      | 'try' ':' suite 'finally' ':' suite */
  2580.     if (TYPE(CHILD(n, 3)) != except_clause)
  2581.         com_try_finally(c, n);
  2582.     else
  2583.         com_try_except(c, n);
  2584. }
  2585.  
  2586. static node *
  2587. get_rawdocstring(n)
  2588.     node *n;
  2589. {
  2590.     int i;
  2591.  
  2592.   /* Label to avoid tail recursion */
  2593.   next:
  2594.     switch (TYPE(n)) {
  2595.  
  2596.     case suite:
  2597.         if (NCH(n) == 1) {
  2598.             n = CHILD(n, 0);
  2599.             goto next;
  2600.         }
  2601.         /* Fall through */
  2602.     case file_input:
  2603.         for (i = 0; i < NCH(n); i++) {
  2604.             node *ch = CHILD(n, i);
  2605.             if (TYPE(ch) == stmt) {
  2606.                 n = ch;
  2607.                 goto next;
  2608.             }
  2609.         }
  2610.         break;
  2611.  
  2612.     case stmt:
  2613.     case simple_stmt:
  2614.     case small_stmt:
  2615.         n = CHILD(n, 0);
  2616.         goto next;
  2617.  
  2618.     case expr_stmt:
  2619.     case testlist:
  2620.     case test:
  2621.     case and_test:
  2622.     case not_test:
  2623.     case comparison:
  2624.     case expr:
  2625.     case xor_expr:
  2626.     case and_expr:
  2627.     case shift_expr:
  2628.     case arith_expr:
  2629.     case term:
  2630.     case factor:
  2631.     case power:
  2632.         if (NCH(n) == 1) {
  2633.             n = CHILD(n, 0);
  2634.             goto next;
  2635.         }
  2636.         break;
  2637.  
  2638.     case atom:
  2639.         if (TYPE(CHILD(n, 0)) == STRING)
  2640.             return n;
  2641.         break;
  2642.  
  2643.     }
  2644.     return NULL;
  2645. }
  2646.  
  2647. static PyObject *
  2648. get_docstring(n)
  2649.     node *n;
  2650. {
  2651.     /* Don't generate doc-strings if run with -OO */
  2652.     if (Py_OptimizeFlag > 1)
  2653.         return NULL;
  2654.     n = get_rawdocstring(n);
  2655.     if (n == NULL)
  2656.         return NULL;
  2657.     return parsestrplus(n);
  2658. }
  2659.  
  2660. static void
  2661. com_suite(c, n)
  2662.     struct compiling *c;
  2663.     node *n;
  2664. {
  2665.     REQ(n, suite);
  2666.     /* simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT */
  2667.     if (NCH(n) == 1) {
  2668.         com_node(c, CHILD(n, 0));
  2669.     }
  2670.     else {
  2671.         int i;
  2672.         for (i = 0; i < NCH(n); i++) {
  2673.             node *ch = CHILD(n, i);
  2674.             if (TYPE(ch) == stmt)
  2675.                 com_node(c, ch);
  2676.         }
  2677.     }
  2678. }
  2679.  
  2680. /* ARGSUSED */
  2681. static void
  2682. com_continue_stmt(c, n)
  2683.     struct compiling *c;
  2684.     node *n; /* Not used, but passed for consistency */
  2685. {
  2686.     int i = c->c_nblocks;
  2687.     if (i-- > 0 && c->c_block[i] == SETUP_LOOP) {
  2688.         com_addoparg(c, JUMP_ABSOLUTE, c->c_begin);
  2689.     }
  2690.     else {
  2691.         com_error(c, PyExc_SyntaxError,
  2692.               "'continue' not properly in loop");
  2693.     }
  2694.     /* XXX Could allow it inside a 'finally' clause
  2695.        XXX if we could pop the exception still on the stack */
  2696. }
  2697.  
  2698. static int
  2699. com_argdefs(c, n)
  2700.     struct compiling *c;
  2701.     node *n;
  2702. {
  2703.     int i, nch, nargs, ndefs;
  2704.     if (TYPE(n) == lambdef) {
  2705.         /* lambdef: 'lambda' [varargslist] ':' test */
  2706.         n = CHILD(n, 1);
  2707.     }
  2708.     else {
  2709.         REQ(n, funcdef); /* funcdef: 'def' NAME parameters ... */
  2710.         n = CHILD(n, 2);
  2711.         REQ(n, parameters); /* parameters: '(' [varargslist] ')' */
  2712.         n = CHILD(n, 1);
  2713.     }
  2714.     if (TYPE(n) != varargslist)
  2715.             return 0;
  2716.     /* varargslist:
  2717.         (fpdef ['=' test] ',')* '*' ....... |
  2718.         fpdef ['=' test] (',' fpdef ['=' test])* [','] */
  2719.     nch = NCH(n);
  2720.     nargs = 0;
  2721.     ndefs = 0;
  2722.     for (i = 0; i < nch; i++) {
  2723.         int t;
  2724.         if (TYPE(CHILD(n, i)) == STAR ||
  2725.             TYPE(CHILD(n, i)) == DOUBLESTAR)
  2726.             break;
  2727.         nargs++;
  2728.         i++;
  2729.         if (i >= nch)
  2730.             t = RPAR; /* Anything except EQUAL or COMMA */
  2731.         else
  2732.             t = TYPE(CHILD(n, i));
  2733.         if (t == EQUAL) {
  2734.             i++;
  2735.             ndefs++;
  2736.             com_node(c, CHILD(n, i));
  2737.             i++;
  2738.             if (i >= nch)
  2739.                 break;
  2740.             t = TYPE(CHILD(n, i));
  2741.         }
  2742.         else {
  2743.             /* Treat "(a=1, b)" as an error */
  2744.             if (ndefs)
  2745.                 com_error(c, PyExc_SyntaxError,
  2746.                 "non-default argument follows default argument");
  2747.         }
  2748.         if (t != COMMA)
  2749.             break;
  2750.     }
  2751.     return ndefs;
  2752. }
  2753.  
  2754. static void
  2755. com_funcdef(c, n)
  2756.     struct compiling *c;
  2757.     node *n;
  2758. {
  2759.     PyObject *v;
  2760.     REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */
  2761.     v = (PyObject *)icompile(n, c);
  2762.     if (v == NULL)
  2763.         c->c_errors++;
  2764.     else {
  2765.         int i = com_addconst(c, v);
  2766.         int ndefs = com_argdefs(c, n);
  2767.         com_addoparg(c, LOAD_CONST, i);
  2768.         com_push(c, 1);
  2769.         com_addoparg(c, MAKE_FUNCTION, ndefs);
  2770.         com_pop(c, ndefs);
  2771.         com_addopname(c, STORE_NAME, CHILD(n, 1));
  2772.         com_pop(c, 1);
  2773.         Py_DECREF(v);
  2774.     }
  2775. }
  2776.  
  2777. static void
  2778. com_bases(c, n)
  2779.     struct compiling *c;
  2780.     node *n;
  2781. {
  2782.     int i;
  2783.     REQ(n, testlist);
  2784.     /* testlist: test (',' test)* [','] */
  2785.     for (i = 0; i < NCH(n); i += 2)
  2786.         com_node(c, CHILD(n, i));
  2787.     i = (NCH(n)+1) / 2;
  2788.     com_addoparg(c, BUILD_TUPLE, i);
  2789.     com_pop(c, i-1);
  2790. }
  2791.  
  2792. static void
  2793. com_classdef(c, n)
  2794.     struct compiling *c;
  2795.     node *n;
  2796. {
  2797.     int i;
  2798.     PyObject *v;
  2799.     REQ(n, classdef);
  2800.     /* classdef: class NAME ['(' testlist ')'] ':' suite */
  2801.     if ((v = PyString_InternFromString(STR(CHILD(n, 1)))) == NULL) {
  2802.         c->c_errors++;
  2803.         return;
  2804.     }
  2805.     /* Push the class name on the stack */
  2806.     i = com_addconst(c, v);
  2807.     com_addoparg(c, LOAD_CONST, i);
  2808.     com_push(c, 1);
  2809.     Py_DECREF(v);
  2810.     /* Push the tuple of base classes on the stack */
  2811.     if (TYPE(CHILD(n, 2)) != LPAR) {
  2812.         com_addoparg(c, BUILD_TUPLE, 0);
  2813.         com_push(c, 1);
  2814.     }
  2815.     else
  2816.         com_bases(c, CHILD(n, 3));
  2817.     v = (PyObject *)icompile(n, c);
  2818.     if (v == NULL)
  2819.         c->c_errors++;
  2820.     else {
  2821.         i = com_addconst(c, v);
  2822.         com_addoparg(c, LOAD_CONST, i);
  2823.         com_push(c, 1);
  2824.         com_addoparg(c, MAKE_FUNCTION, 0);
  2825.         com_addoparg(c, CALL_FUNCTION, 0);
  2826.         com_addbyte(c, BUILD_CLASS);
  2827.         com_pop(c, 2);
  2828.         com_addopname(c, STORE_NAME, CHILD(n, 1));
  2829.         Py_DECREF(v);
  2830.     }
  2831. }
  2832.  
  2833. static void
  2834. com_node(c, n)
  2835.     struct compiling *c;
  2836.     node *n;
  2837. {
  2838.     switch (TYPE(n)) {
  2839.     
  2840.     /* Definition nodes */
  2841.     
  2842.     case funcdef:
  2843.         com_funcdef(c, n);
  2844.         break;
  2845.     case classdef:
  2846.         com_classdef(c, n);
  2847.         break;
  2848.     
  2849.     /* Trivial parse tree nodes */
  2850.     
  2851.     case stmt:
  2852.     case small_stmt:
  2853.     case flow_stmt:
  2854.         com_node(c, CHILD(n, 0));
  2855.         break;
  2856.  
  2857.     case simple_stmt:
  2858.         /* small_stmt (';' small_stmt)* [';'] NEWLINE */
  2859.         com_addoparg(c, SET_LINENO, n->n_lineno);
  2860.         {
  2861.             int i;
  2862.             for (i = 0; i < NCH(n)-1; i += 2)
  2863.                 com_node(c, CHILD(n, i));
  2864.         }
  2865.         break;
  2866.     
  2867.     case compound_stmt:
  2868.         com_addoparg(c, SET_LINENO, n->n_lineno);
  2869.         com_node(c, CHILD(n, 0));
  2870.         break;
  2871.  
  2872.     /* Statement nodes */
  2873.     
  2874.     case expr_stmt:
  2875.         com_expr_stmt(c, n);
  2876.         break;
  2877.     case print_stmt:
  2878.         com_print_stmt(c, n);
  2879.         break;
  2880.     case del_stmt: /* 'del' exprlist */
  2881.         com_assign(c, CHILD(n, 1), OP_DELETE);
  2882.         break;
  2883.     case pass_stmt:
  2884.         break;
  2885.     case break_stmt:
  2886.         if (c->c_loops == 0) {
  2887.             com_error(c, PyExc_SyntaxError,
  2888.                   "'break' outside loop");
  2889.         }
  2890.         com_addbyte(c, BREAK_LOOP);
  2891.         break;
  2892.     case continue_stmt:
  2893.         com_continue_stmt(c, n);
  2894.         break;
  2895.     case return_stmt:
  2896.         com_return_stmt(c, n);
  2897.         break;
  2898.     case raise_stmt:
  2899.         com_raise_stmt(c, n);
  2900.         break;
  2901.     case import_stmt:
  2902.         com_import_stmt(c, n);
  2903.         break;
  2904.     case global_stmt:
  2905.         com_global_stmt(c, n);
  2906.         break;
  2907.     case exec_stmt:
  2908.         com_exec_stmt(c, n);
  2909.         break;
  2910.     case assert_stmt:
  2911.         com_assert_stmt(c, n);
  2912.         break;
  2913.     case if_stmt:
  2914.         com_if_stmt(c, n);
  2915.         break;
  2916.     case while_stmt:
  2917.         com_while_stmt(c, n);
  2918.         break;
  2919.     case for_stmt:
  2920.         com_for_stmt(c, n);
  2921.         break;
  2922.     case try_stmt:
  2923.         com_try_stmt(c, n);
  2924.         break;
  2925.     case suite:
  2926.         com_suite(c, n);
  2927.         break;
  2928.     
  2929.     /* Expression nodes */
  2930.     
  2931.     case testlist:
  2932.         com_list(c, n, 0);
  2933.         break;
  2934.     case test:
  2935.         com_test(c, n);
  2936.         break;
  2937.     case and_test:
  2938.         com_and_test(c, n);
  2939.         break;
  2940.     case not_test:
  2941.         com_not_test(c, n);
  2942.         break;
  2943.     case comparison:
  2944.         com_comparison(c, n);
  2945.         break;
  2946.     case exprlist:
  2947.         com_list(c, n, 0);
  2948.         break;
  2949.     case expr:
  2950.         com_expr(c, n);
  2951.         break;
  2952.     case xor_expr:
  2953.         com_xor_expr(c, n);
  2954.         break;
  2955.     case and_expr:
  2956.         com_and_expr(c, n);
  2957.         break;
  2958.     case shift_expr:
  2959.         com_shift_expr(c, n);
  2960.         break;
  2961.     case arith_expr:
  2962.         com_arith_expr(c, n);
  2963.         break;
  2964.     case term:
  2965.         com_term(c, n);
  2966.         break;
  2967.     case factor:
  2968.         com_factor(c, n);
  2969.         break;
  2970.     case power:
  2971.         com_power(c, n);
  2972.         break;
  2973.     case atom:
  2974.         com_atom(c, n);
  2975.         break;
  2976.     
  2977.     default:
  2978.         /* XXX fprintf(stderr, "node type %d\n", TYPE(n)); */
  2979.         com_error(c, PyExc_SystemError,
  2980.               "com_node: unexpected node type");
  2981.     }
  2982. }
  2983.  
  2984. static void com_fplist Py_PROTO((struct compiling *, node *));
  2985.  
  2986. static void
  2987. com_fpdef(c, n)
  2988.     struct compiling *c;
  2989.     node *n;
  2990. {
  2991.     REQ(n, fpdef); /* fpdef: NAME | '(' fplist ')' */
  2992.     if (TYPE(CHILD(n, 0)) == LPAR)
  2993.         com_fplist(c, CHILD(n, 1));
  2994.     else {
  2995.         com_addoparg(c, STORE_FAST, com_newlocal(c, STR(CHILD(n, 0))));
  2996.         com_pop(c, 1);
  2997.     }
  2998. }
  2999.  
  3000. static void
  3001. com_fplist(c, n)
  3002.     struct compiling *c;
  3003.     node *n;
  3004. {
  3005.     REQ(n, fplist); /* fplist: fpdef (',' fpdef)* [','] */
  3006.     if (NCH(n) == 1) {
  3007.         com_fpdef(c, CHILD(n, 0));
  3008.     }
  3009.     else {
  3010.         int i = (NCH(n)+1)/2;
  3011.         com_addoparg(c, UNPACK_TUPLE, i);
  3012.         com_push(c, i-1);
  3013.         for (i = 0; i < NCH(n); i += 2)
  3014.             com_fpdef(c, CHILD(n, i));
  3015.     }
  3016. }
  3017.  
  3018. static void
  3019. com_arglist(c, n)
  3020.     struct compiling *c;
  3021.     node *n;
  3022. {
  3023.     int nch, i;
  3024.     int complex = 0;
  3025.     char nbuf[10];
  3026.     REQ(n, varargslist);
  3027.     /* varargslist:
  3028.         (fpdef ['=' test] ',')* (fpdef ['=' test] | '*' .....) */
  3029.     nch = NCH(n);
  3030.     /* Enter all arguments in table of locals */
  3031.     for (i = 0; i < nch; i++) {
  3032.         node *ch = CHILD(n, i);
  3033.         node *fp;
  3034.         char *name;
  3035.         if (TYPE(ch) == STAR || TYPE(ch) == DOUBLESTAR)
  3036.             break;
  3037.         REQ(ch, fpdef); /* fpdef: NAME | '(' fplist ')' */
  3038.         fp = CHILD(ch, 0);
  3039.         if (TYPE(fp) == NAME)
  3040.             name = STR(fp);
  3041.         else {
  3042.             name = nbuf;
  3043.             sprintf(nbuf, ".%d", i);
  3044.             complex = 1;
  3045.         }
  3046.         com_newlocal(c, name);
  3047.         c->c_argcount++;
  3048.         if (++i >= nch)
  3049.             break;
  3050.         ch = CHILD(n, i);
  3051.         if (TYPE(ch) == EQUAL)
  3052.             i += 2;
  3053.         else
  3054.             REQ(ch, COMMA);
  3055.     }
  3056.     /* Handle *arguments */
  3057.     if (i < nch) {
  3058.         node *ch;
  3059.         ch = CHILD(n, i);
  3060.         if (TYPE(ch) != DOUBLESTAR) {
  3061.             REQ(ch, STAR);
  3062.             ch = CHILD(n, i+1);
  3063.             if (TYPE(ch) == NAME) {
  3064.                 c->c_flags |= CO_VARARGS;
  3065.                 i += 3;
  3066.                 com_newlocal(c, STR(ch));
  3067.             }
  3068.         }
  3069.     }
  3070.     /* Handle **keywords */
  3071.     if (i < nch) {
  3072.         node *ch;
  3073.         ch = CHILD(n, i);
  3074.         if (TYPE(ch) != DOUBLESTAR) {
  3075.             REQ(ch, STAR);
  3076.             ch = CHILD(n, i+1);
  3077.             REQ(ch, STAR);
  3078.             ch = CHILD(n, i+2);
  3079.         }
  3080.         else
  3081.             ch = CHILD(n, i+1);
  3082.         REQ(ch, NAME);
  3083.         c->c_flags |= CO_VARKEYWORDS;
  3084.         com_newlocal(c, STR(ch));
  3085.     }
  3086.     if (complex) {
  3087.         /* Generate code for complex arguments only after
  3088.            having counted the simple arguments */
  3089.         int ilocal = 0;
  3090.         for (i = 0; i < nch; i++) {
  3091.             node *ch = CHILD(n, i);
  3092.             node *fp;
  3093.             if (TYPE(ch) == STAR || TYPE(ch) == DOUBLESTAR)
  3094.                 break;
  3095.             REQ(ch, fpdef); /* fpdef: NAME | '(' fplist ')' */
  3096.             fp = CHILD(ch, 0);
  3097.             if (TYPE(fp) != NAME) {
  3098.                 com_addoparg(c, LOAD_FAST, ilocal);
  3099.                 com_push(c, 1);
  3100.                 com_fpdef(c, ch);
  3101.             }
  3102.             ilocal++;
  3103.             if (++i >= nch)
  3104.                 break;
  3105.             ch = CHILD(n, i);
  3106.             if (TYPE(ch) == EQUAL)
  3107.                 i += 2;
  3108.             else
  3109.                 REQ(ch, COMMA);
  3110.         }
  3111.     }
  3112. }
  3113.  
  3114. static void
  3115. com_file_input(c, n)
  3116.     struct compiling *c;
  3117.     node *n;
  3118. {
  3119.     int i;
  3120.     PyObject *doc;
  3121.     REQ(n, file_input); /* (NEWLINE | stmt)* ENDMARKER */
  3122.     doc = get_docstring(n);
  3123.     if (doc != NULL) {
  3124.         int i = com_addconst(c, doc);
  3125.         Py_DECREF(doc);
  3126.         com_addoparg(c, LOAD_CONST, i);
  3127.         com_push(c, 1);
  3128.         com_addopnamestr(c, STORE_NAME, "__doc__");
  3129.         com_pop(c, 1);
  3130.     }
  3131.     for (i = 0; i < NCH(n); i++) {
  3132.         node *ch = CHILD(n, i);
  3133.         if (TYPE(ch) != ENDMARKER && TYPE(ch) != NEWLINE)
  3134.             com_node(c, ch);
  3135.     }
  3136. }
  3137.  
  3138. /* Top-level compile-node interface */
  3139.  
  3140. static void
  3141. compile_funcdef(c, n)
  3142.     struct compiling *c;
  3143.     node *n;
  3144. {
  3145.     PyObject *doc;
  3146.     node *ch;
  3147.     REQ(n, funcdef); /* funcdef: 'def' NAME parameters ':' suite */
  3148.     c->c_name = STR(CHILD(n, 1));
  3149.     doc = get_docstring(CHILD(n, 4));
  3150.     if (doc != NULL) {
  3151.         (void) com_addconst(c, doc);
  3152.         Py_DECREF(doc);
  3153.     }
  3154.     else
  3155.         (void) com_addconst(c, Py_None); /* No docstring */
  3156.     ch = CHILD(n, 2); /* parameters: '(' [varargslist] ')' */
  3157.     ch = CHILD(ch, 1); /* ')' | varargslist */
  3158.     if (TYPE(ch) == varargslist)
  3159.         com_arglist(c, ch);
  3160.     c->c_infunction = 1;
  3161.     com_node(c, CHILD(n, 4));
  3162.     c->c_infunction = 0;
  3163.     com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  3164.     com_push(c, 1);
  3165.     com_addbyte(c, RETURN_VALUE);
  3166.     com_pop(c, 1);
  3167. }
  3168.  
  3169. static void
  3170. compile_lambdef(c, n)
  3171.     struct compiling *c;
  3172.     node *n;
  3173. {
  3174.     node *ch;
  3175.     REQ(n, lambdef); /* lambdef: 'lambda' [varargslist] ':' test */
  3176.     c->c_name = "<lambda>";
  3177.  
  3178.     ch = CHILD(n, 1);
  3179.     (void) com_addconst(c, Py_None); /* No docstring */
  3180.     if (TYPE(ch) == varargslist) {
  3181.         com_arglist(c, ch);
  3182.         ch = CHILD(n, 3);
  3183.     }
  3184.     else
  3185.         ch = CHILD(n, 2);
  3186.     com_node(c, ch);
  3187.     com_addbyte(c, RETURN_VALUE);
  3188.     com_pop(c, 1);
  3189. }
  3190.  
  3191. static void
  3192. compile_classdef(c, n)
  3193.     struct compiling *c;
  3194.     node *n;
  3195. {
  3196.     node *ch;
  3197.     PyObject *doc;
  3198.     REQ(n, classdef);
  3199.     /* classdef: 'class' NAME ['(' testlist ')'] ':' suite */
  3200.     c->c_name = STR(CHILD(n, 1));
  3201. #ifdef PRIVATE_NAME_MANGLING
  3202.     c->c_private = c->c_name;
  3203. #endif
  3204.     ch = CHILD(n, NCH(n)-1); /* The suite */
  3205.     doc = get_docstring(ch);
  3206.     if (doc != NULL) {
  3207.         int i = com_addconst(c, doc);
  3208.         Py_DECREF(doc);
  3209.         com_addoparg(c, LOAD_CONST, i);
  3210.         com_push(c, 1);
  3211.         com_addopnamestr(c, STORE_NAME, "__doc__");
  3212.         com_pop(c, 1);
  3213.     }
  3214.     else
  3215.         (void) com_addconst(c, Py_None);
  3216.     com_node(c, ch);
  3217.     com_addbyte(c, LOAD_LOCALS);
  3218.     com_push(c, 1);
  3219.     com_addbyte(c, RETURN_VALUE);
  3220.     com_pop(c, 1);
  3221. }
  3222.  
  3223. static void
  3224. compile_node(c, n)
  3225.     struct compiling *c;
  3226.     node *n;
  3227. {
  3228.     com_addoparg(c, SET_LINENO, n->n_lineno);
  3229.     
  3230.     switch (TYPE(n)) {
  3231.     
  3232.     case single_input: /* One interactive command */
  3233.         /* NEWLINE | simple_stmt | compound_stmt NEWLINE */
  3234.         c->c_interactive++;
  3235.         n = CHILD(n, 0);
  3236.         if (TYPE(n) != NEWLINE)
  3237.             com_node(c, n);
  3238.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  3239.         com_push(c, 1);
  3240.         com_addbyte(c, RETURN_VALUE);
  3241.         com_pop(c, 1);
  3242.         c->c_interactive--;
  3243.         break;
  3244.     
  3245.     case file_input: /* A whole file, or built-in function exec() */
  3246.         com_file_input(c, n);
  3247.         com_addoparg(c, LOAD_CONST, com_addconst(c, Py_None));
  3248.         com_push(c, 1);
  3249.         com_addbyte(c, RETURN_VALUE);
  3250.         com_pop(c, 1);
  3251.         break;
  3252.     
  3253.     case eval_input: /* Built-in function input() */
  3254.         com_node(c, CHILD(n, 0));
  3255.         com_addbyte(c, RETURN_VALUE);
  3256.         com_pop(c, 1);
  3257.         break;
  3258.     
  3259.     case lambdef: /* anonymous function definition */
  3260.         compile_lambdef(c, n);
  3261.         break;
  3262.  
  3263.     case funcdef: /* A function definition */
  3264.         compile_funcdef(c, n);
  3265.         break;
  3266.     
  3267.     case classdef: /* A class definition */
  3268.         compile_classdef(c, n);
  3269.         break;
  3270.     
  3271.     default:
  3272.         /* XXX fprintf(stderr, "node type %d\n", TYPE(n)); */
  3273.         com_error(c, PyExc_SystemError,
  3274.               "compile_node: unexpected node type");
  3275.     }
  3276. }
  3277.  
  3278. /* Optimization for local variables in functions (and *only* functions).
  3279.  
  3280.    This replaces all LOAD_NAME, STORE_NAME and DELETE_NAME
  3281.    instructions that refer to local variables with LOAD_FAST etc.
  3282.    The latter instructions are much faster because they don't need to
  3283.    look up the variable name in a dictionary.
  3284.  
  3285.    To find all local variables, we check all STORE_NAME, IMPORT_FROM
  3286.    and DELETE_NAME instructions.  This yields all local variables,
  3287.    function definitions, class definitions and import statements.
  3288.    Argument names have already been entered into the list by the
  3289.    special processing for the argument list.
  3290.  
  3291.    All remaining LOAD_NAME instructions must refer to non-local (global
  3292.    or builtin) variables, so are replaced by LOAD_GLOBAL.
  3293.  
  3294.    There are two problems:  'from foo import *' and 'exec' may introduce
  3295.    local variables that we can't know while compiling.  If this is the
  3296.    case, we can still optimize bona fide locals (since those
  3297.    statements will be surrounded by fast_2_locals() and
  3298.    locals_2_fast()), but we can't change LOAD_NAME to LOAD_GLOBAL.
  3299.  
  3300.    NB: this modifies the string object c->c_code!  */
  3301.  
  3302. static void
  3303. optimize(c)
  3304.     struct compiling *c;
  3305. {
  3306.     unsigned char *next_instr, *cur_instr;
  3307.     int opcode;
  3308.     int oparg = 0;
  3309.     PyObject *name;
  3310.     PyObject *error_type, *error_value, *error_traceback;
  3311.     
  3312. #define NEXTOP()    (*next_instr++)
  3313. #define NEXTARG()    (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
  3314. #define GETITEM(v, i)    (PyList_GetItem((v), (i)))
  3315. #define GETNAMEOBJ(i)    (GETITEM(c->c_names, (i)))
  3316.     
  3317.     PyErr_Fetch(&error_type, &error_value, &error_traceback);
  3318.  
  3319.     c->c_flags |= CO_OPTIMIZED;
  3320.     
  3321.     next_instr = (unsigned char *) PyString_AsString(c->c_code);
  3322.     for (;;) {
  3323.         opcode = NEXTOP();
  3324.         if (opcode == STOP_CODE)
  3325.             break;
  3326.         if (HAS_ARG(opcode))
  3327.             oparg = NEXTARG();
  3328.         switch (opcode) {
  3329.         case STORE_NAME:
  3330.         case DELETE_NAME:
  3331.         case IMPORT_FROM:
  3332.             com_addlocal_o(c, GETNAMEOBJ(oparg));
  3333.             break;
  3334.         case EXEC_STMT:
  3335.             c->c_flags &= ~CO_OPTIMIZED;
  3336.             break;
  3337.         }
  3338.     }
  3339.     
  3340.     if (PyDict_GetItemString(c->c_locals, "*") != NULL)
  3341.         c->c_flags &= ~CO_OPTIMIZED;
  3342.     
  3343.     next_instr = (unsigned char *) PyString_AsString(c->c_code);
  3344.     for (;;) {
  3345.         cur_instr = next_instr;
  3346.         opcode = NEXTOP();
  3347.         if (opcode == STOP_CODE)
  3348.             break;
  3349.         if (HAS_ARG(opcode))
  3350.             oparg = NEXTARG();
  3351.         if (opcode == LOAD_NAME ||
  3352.             opcode == STORE_NAME ||
  3353.             opcode == DELETE_NAME) {
  3354.             PyObject *v;
  3355.             int i;
  3356.             name = GETNAMEOBJ(oparg);
  3357.             v = PyDict_GetItem(c->c_locals, name);
  3358.             if (v == NULL) {
  3359.                 if (opcode == LOAD_NAME &&
  3360.                     (c->c_flags&CO_OPTIMIZED))
  3361.                     cur_instr[0] = LOAD_GLOBAL;
  3362.                 continue;
  3363.             }
  3364.             i = PyInt_AsLong(v);
  3365.             switch (opcode) {
  3366.             case LOAD_NAME: cur_instr[0] = LOAD_FAST; break;
  3367.             case STORE_NAME: cur_instr[0] = STORE_FAST; break;
  3368.             case DELETE_NAME: cur_instr[0] = DELETE_FAST; break;
  3369.             }
  3370.             cur_instr[1] = i & 0xff;
  3371.             cur_instr[2] = (i>>8) & 0xff;
  3372.         }
  3373.     }
  3374.  
  3375.     if (c->c_errors == 0)
  3376.         PyErr_Restore(error_type, error_value, error_traceback);
  3377. }
  3378.  
  3379. PyCodeObject *
  3380. PyNode_Compile(n, filename)
  3381.     node *n;
  3382.     char *filename;
  3383. {
  3384.     return jcompile(n, filename, NULL);
  3385. }
  3386.  
  3387. static PyCodeObject *
  3388. icompile(n, base)
  3389.     node *n;
  3390.     struct compiling *base;
  3391. {
  3392.     return jcompile(n, base->c_filename, base);
  3393. }
  3394.  
  3395. static PyCodeObject *
  3396. jcompile(n, filename, base)
  3397.     node *n;
  3398.     char *filename;
  3399.     struct compiling *base;
  3400. {
  3401.     struct compiling sc;
  3402.     PyCodeObject *co;
  3403.     if (!com_init(&sc, filename))
  3404.         return NULL;
  3405. #ifdef PRIVATE_NAME_MANGLING
  3406.     if (base)
  3407.         sc.c_private = base->c_private;
  3408.     else
  3409.         sc.c_private = NULL;
  3410. #endif
  3411.     compile_node(&sc, n);
  3412.     com_done(&sc);
  3413.     if ((TYPE(n) == funcdef || TYPE(n) == lambdef) && sc.c_errors == 0) {
  3414.         optimize(&sc);
  3415.         sc.c_flags |= CO_NEWLOCALS;
  3416.     }
  3417.     else if (TYPE(n) == classdef)
  3418.         sc.c_flags |= CO_NEWLOCALS;
  3419.     co = NULL;
  3420.     if (sc.c_errors == 0) {
  3421.         PyObject *consts, *names, *varnames, *filename, *name;
  3422.         consts = PyList_AsTuple(sc.c_consts);
  3423.         names = PyList_AsTuple(sc.c_names);
  3424.         varnames = PyList_AsTuple(sc.c_varnames);
  3425.         filename = PyString_InternFromString(sc.c_filename);
  3426.         name = PyString_InternFromString(sc.c_name);
  3427.         if (!PyErr_Occurred())
  3428.             co = PyCode_New(sc.c_argcount,
  3429.                        sc.c_nlocals,
  3430.                        sc.c_maxstacklevel,
  3431.                        sc.c_flags,
  3432.                        sc.c_code,
  3433.                        consts,
  3434.                        names,
  3435.                        varnames,
  3436.                        filename,
  3437.                        name,
  3438.                        sc.c_firstlineno,
  3439.                        sc.c_lnotab);
  3440.         Py_XDECREF(consts);
  3441.         Py_XDECREF(names);
  3442.         Py_XDECREF(varnames);
  3443.         Py_XDECREF(filename);
  3444.         Py_XDECREF(name);
  3445.     }
  3446.     com_free(&sc);
  3447.     return co;
  3448. }
  3449.  
  3450. int
  3451. PyCode_Addr2Line(co, addrq)
  3452.     PyCodeObject *co;
  3453.     int addrq;
  3454. {
  3455.     int size = PyString_Size(co->co_lnotab) / 2;
  3456.     char *p = PyString_AsString(co->co_lnotab);
  3457.     int line = co->co_firstlineno;
  3458.     int addr = 0;
  3459.     while (--size >= 0) {
  3460.         addr += *p++;
  3461.         if (addr > addrq)
  3462.             break;
  3463.         line += *p++;
  3464.     }
  3465.     return line;
  3466. }
  3467.